我正在尝试学习 Node js。我试图通过前端从 axios 发出一个发布请求,但 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))
将以 JSON 形式发送 POST 请求的正文。直接引用自 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');
});
注意,无需单独加载 body-parser 模块,因为它内置于 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());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
同时使用两者,而不是仅使用一种。