[英]Axios post method is sending a object with my data as the key and empty value rather than the whole data object itself
我先做了前端,现在我想做后端,这样我就可以连接到数据库。
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.send("hello");
});
app.post("/", function (req, res) {
console.log(req.body);
});
app.listen(3001, function () {
console.log("listening on 3001");
});
这是我在 React 前端提出的请求。
axios.post("http://localhost:3001/", JSON.stringify(note));
note
是一个像{title: "",content: ""}
的对象,空字符串被填写提交数据。
当我发出发布请求时,这就是在控制台中记录的内容
{ '{"title":"test","content":"one"}': '' }
我必须使用 JSON.stringify() 来显示正在传递的内容,但没有它,我的输出是 {}
当我的对象被发布时,它成为具有空值的对象的键。
我想要做的只是像这样发送整个对象
axios.post("http://localhost:3001/", note);
这样在后端我可以通过执行req.body.title
和req.body.content
来利用这些值。
必要的正文解析中间件是express.json()
:
app.post("/", express.json(), function (req, res) {
console.log(req.body);
});
这要求请求具有标头Content-Type: application/json
。
嘿不是答案,但如果你解决了这个问题,你能告诉我怎么做吗? 我也遇到了同样的问题!
编辑-> 所以我不使用app.use(bodyParser.urlencoded({extended: true})
我使用app.use(express.json())
现在我收到了很好的空对象,如果我得到任何解决方案将更新
编辑->所以这是我的代码,它工作得很好
const data = qs.stringify(question); const options = { method: 'post', url: 'http://localhost:3100/admin', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, data: data, };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.