首页 > 解决方案 > req.body.something 返回未定义

问题描述

我一直在尝试使用 axios 将数据发布到我的快速服务器,当我 console.log(req.body.something) 它返回未定义时,当我 console.log(req.body) 只将此消息记录到控制台: [Object: null prototype] { '{"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)});

};

标签: reactjsexpressaxios

解决方案


如果您Content-Type从 axios 请求中删除您的自定义标头,则 axios 默认将您的数据作为 JSON 发送,并且它将由您的快速 JSON 解析器中间件解析。

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

您发送到服务器的数据是nameValand nickNameVal,因此尝试访问req.body.name仍然会给出undefined。尝试记录nameValnickNameVal而不是。

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

推荐阅读