【问题标题】:req.body.something returns undefinedreq.body.something 返回未定义
【发布时间】: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)});

};

【问题讨论】:

    标签: reactjs express axios


    【解决方案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);
    });
    

    【讨论】:

    • 是的,有道理,谢谢先生 :)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 1970-01-01
      • 2016-11-18
      • 2019-12-24
      • 2016-05-15
      • 2017-03-11
      • 2020-10-02
      • 2020-05-22
      • 2018-10-02
      相关资源
      最近更新 更多