req.body.something返回未定义

时间:2019-02-14 21:53:45

标签: reactjs express axios

我一直在尝试使用axios将数据发布到我的Express服务器,当我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)});

};

2 个答案:

答案 0 :(得分:1)

如果您从axios请求中删除了自定义Content-Type标头,则axios默认情况下将以JSON格式发送您的数据,并且将由您的快速JSON解析器中间件进行解析。

axios.post("http://localhost:5000/user", { nameVal, nickNameVal })
  .then(res => console.log(res));

您发送到服务器的数据是nameValnickNameVal,因此尝试访问req.body.name仍会得到undefined。尝试登录nameValnickNameVal

app.post("/user", (req, res) => {
  console.log(req.body.nameVal, req.body.nickNameVal);
});

答案 1 :(得分:0)

根据axios documentation,您需要传递URLSearchParams的实例(或参数的查询字符串)作为第二个参数。

const params = new URLSearchParams();
params.append('nameVal', state.nameVal);
params.append('nickNameVal', state.nickNameVal);
axios.post('/user', params);
相关问题