将请求主体发布为空-XMLHttpRequest到Express服务器

时间:2019-06-09 21:05:29

标签: javascript node.js express post xmlhttprequest

我正在尝试使用XMLHttpRequest发送到快速服务器的发布请求中访问正文。但是请求的内容为空,我似乎无法理解为什么会这样。

我在express应用程序中包含了一个正文解析器,并且我尝试从SO答案中复制一些代码。但是我仍然以某种方式弄错了。

<script>
    const Http = new XMLHttpRequest();
    Http.open('post', 'localhost:3000');
    Http.send("sending something!");// this resolves to {} on the backend?
    Http.onload = function() {
     alert(Http.response); 
    };
</script>

这就是我尝试在快递服务器上处理它的方式

const express = require("express");
let app = express()
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: true
}));
app.post("/post", (req, res) => {
    console.log("inside of post");
    console.log(req.body);
})

app.listen(3000)

这是日志

inside of post
{}

我希望console.log()打印“正在发送东西!”我尝试与Http.send("sending something!");一起发送请求。

1 个答案:

答案 0 :(得分:2)

您已指定body-parser来将正文解析为url编码格式,如果您传递这样的数据,该格式将起作用:

Http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Http.send("param1=value1&param2=value2");

/* console output:
{ param1: 'value1', param2: 'value2' }
*/

在您的情况下,要传递的数据是简单的字符串,由于无法解析,后端会将其解释为空的JSON {}

要使其正常工作,请尝试如下设置数据格式

<script>
    const Http = new XMLHttpRequest();
    Http.open('post', 'localhost:3000');
    Http.setRequestHeader("Content-Type", "text/plain");
    Http.send("sending something!");
    Http.onload = function() {
     alert(Http.response); 
    };
</script>

在快递服务器中:

const express = require("express");
let app = express();
const bodyParser = require("body-parser");
// app.use(
//   bodyParser.urlencoded({
//     extended: true
//   })
// );

app.use(bodyParser.text({ type: "text/plain" })); // use this instead

app.post("/post", (req, res) => {
  console.log("inside of post");
  console.log(req.body);
  return req.body;
});

app.listen(3000);

然后,您也许可以在后端阅读消息"sending something!"。 只需确保在发送时在XMLHttpRequest中设置正确的contentType标头,并且在后端解析时也使用相同的类型。

有关bodyParsers的更多信息,请参阅此doc

相关问题