简体   繁体   English

node.js post 请求只返回 undefined

[英]node js post request only returning undefined

I'm trying to make an api call for an online course project but before I can do that I need to retrieve the user input and currently I'm getting undefined responses to my post request.我正在尝试为在线课程项目拨打 api 电话,但在我可以这样做之前,我需要检索用户输入,目前我收到对我的发布请求的未定义响应。 I think these are the relevant parts of my code:我认为这些是我的代码的相关部分:

formHandler.js:表单处理程序.js:


import { postURL } from "./postURL"

function handleSubmit(event) {
    event.preventDefault()

    // check what text was put into the form field
    let url = document.getElementById('URL').value
    postURL('/postURL', url)
    //.then(updateUI());
};

export { handleSubmit }

postURL.js: postURL.js:

let postURL = async(url = '', data = {})=>{
    let response = await fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            "Content-Type": 'application/json',
        },
        body: JSON.stringify( { data} ),
    });
    try {
        console.log(data);
    }catch(error){
        console.log("error", error);
    }
}

export { postURL }

part of index.html: index.html 的一部分:

<form class="form" onsubmit="return Client.handleSubmit(event)">
    <input id="URL" type="text" name="input" value="" placeholder="URL" size="48">
    <input type="submit" id="input" class="button" name="" value="submit" onclick="return Client.handleSubmit(event)" onsubmit="return Client.handleSubmit(event)">
</form>

index.js on server side:服务器端的 index.js:

app.post('/postURL', getURL);

function getURL(req, res){
    console.log(req.body);
    url = req.body;
    console.log(url)
    //apiCall(url)
}

Do you have any idea why the data isn't being returned to /postURL?您知道为什么数据没有返回到 /postURL 吗? I can't figure this out.我想不通。 Any help would be greatly appreciated.任何帮助将不胜感激。

Thank you, Mike谢谢你,迈克

I am not sure if you are receiving undefined in client or server.我不确定您是否在客户端或服务器中收到 undefined。 If you want to receive JSON data in backend, you have to use bodyParser.json in express.如果你想在后端接收 JSON 数据,你必须在 express 中使用 bodyParser.json。 If you want to receive a response in client, just call res.json(your_value), or res.send(yourValue)如果您想在客户端收到响应,只需调用 res.json(your_value) 或 res.send(yourValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM