简体   繁体   English

如何从 XMLHttpRequest 传入参数?

[英]How to pass in a parameter from XMLHttpRequest?

I'm making an experiment with express and XHR .我正在用expressXHR做一个实验。 And I came up with a problem that after passing a params in xhr.send(params) didn't recieve it on the app.post() .我遇到了一个问题,在xhr.send(params)中传递了一个参数后,app.post app.post() ) 没有收到它。 I don't know if my code is correct but here it is.我不知道我的代码是否正确,但在这里。

My app.js file:我的app.js文件:

app.post('/', urlencodedParser, async (req, res) => {
    console.log('Received a request!', req.body); // I also tried req.params, req.query and still the same
    // output: "Recieved a request! {}"
    res.end('respond!');
});

Here's my script.js file:这是我的script.js文件:

xhr.open('POST', '/', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.send(JSON.stringify({
            name: 'SomeName'
        }));

Why is it that the params is empty when I recivied it in the app.js ?为什么当我在app.js中接收它时参数是空的? Is this how you really pass in parameters?这是你真正传递参数的方式吗?

You need this:你需要这个:

app.use(express.json())

somewhere before your app.post() handler.在你的app.post()处理程序之前的某个地方。 That middleware will read the body of the response and parse the JSON and put the resulting Javascript properties into the req.body object for your later request handler to examine.该中间件将读取响应正文并解析 JSON 并将生成的 Javascript 属性放入req.body object 以供您以后的请求处理程序检查。

If you don't have that middleware, then the body of the POST is never read and thus req.body is never populated.如果您没有该中间件,则永远不会读取 POST 的主体,因此永远不会填充req.body

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

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