【发布时间】:2019-07-09 00:36:22
【问题描述】:
我一直在尝试使用 axios 将数据发布到我的快速服务器,当我 console.log(req.body.something) 它返回未定义时,当我 console.log(req.body) 只记录此消息到控制台: [对象:空原型] { '{"nameVal":"Usef","nickNameVal":"US"}': '' } 任何帮助将不胜感激。
// This My Server.js Code
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
const urlencodedparser = bodyParser.urlencoded({ extended: false });
// Use Cors As MiddleWhere
app.use(cors());
// Get The Post Request
app.post("/user", urlencodedparser, (req, res) => {
console.log(req.body.name); // returns undefined
});
app.listen(5000);
// and this the react component state along with the axios post request
state = {
nameVal: "Usef",
nickNameVal: "US"
};
handleSubmit = event => {
event.preventDefault();
const { nameVal, nickNameVal } = this.state;
axios.post("http://localhost:5000/user", { nameVal, nickNameVal },
{ headers: { "Content-Type": "application/x-www-form-urlencoded" } }
).then(res => {console.log(res)});
};
【问题讨论】: