axios在nodejs后端没有收到来自前端的post请求



我正在尝试学习node.js。我试图通过前端从axios发出一个post请求,但node-js的响应是空对象。

这是代码

节点js

var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});

前端

axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))

响应是一个空对象。

我该怎么办?

默认情况下,您的axios代码:

axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))

将POST请求的正文作为JSON发送。直接从axios文档引用。

默认情况下,axios将JavaScript对象序列化为JSON

因此,您需要Express服务器上的JSON中间件来读取和解析JSON主体。如果没有寻找特定内容类型的中间件,POST请求的主体将不会被读取或解析,req.body将保持为空。

app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});

注意,不需要单独加载主体解析器模块,因为它是Express内置的。


或者,如果您希望请求以application/x-www-form-urlencoded内容类型发送,则需要以这种方式对数据进行编码,并将其作为axios请求中的数据发送,并适当设置内容类型。

这些请求体可以由express.urlencoded()中间件以与express.json()相同的方式来处理。

您应该使用bodyParser.json((来获取req.body.中发送的数据

var bodyParser = require('body-parser');
app.use(bodyParser.json());

在使用中间件访问请求体之前,我们应该解析请求体,方法如下

app.use(bodyParser.json());

最新更新