【问题标题】:Empty request body空请求正文
【发布时间】:2017-12-19 15:07:59
【问题描述】:

我生成了两个项目,一个使用 create-react-app,另一个使用 express generator。

我在localhost:3000 上运行第一个,在localhost:3001 上运行第二个。

我正在尝试发送 POST 请求,但收到一个空的 req.body

客户端:

 handleSubmit(event) {
    event.preventDefault();
    var data = new FormData();
    for (const key of Object.keys(this.state)) {
      data.append(key, this.state[key]);
    }

    const url = "http://localhost:3000/course";
    fetch(url, {
      method: "POST",
      body: this.state
    })
      .then(response => response.text())
      .then(html => console.log(html));
  }

服务器端:

app.js

app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use("/course", course);

router/course.js

router.post("/", function(req, res) {
  if (!req.body) {
    var course = new Course(req.body);
    course
      .save()
      .then(item => {
        res.json({ course: item });
      })
      .catch(err => {
        res.status(500).send("Unable to save to database");
      });
  }
  res.status(200).send("No data to save");
});

【问题讨论】:

  • 您是否在package.json 中添加了代理? "proxy": "http://localhost:3001",
  • 不,我为什么要这样做?
  • 不应该body: this.statebody: data??
  • 我都试过了,req.body 总是空的
  • 从你的url变量中删除/course(你的服务器是router.post("/" ...

标签: node.js reactjs express body-parser


【解决方案1】:

body-parser 需要将 Content-Type 标头设置为 'Content-Type': 'application/json' 才能知道必须解析正文

尝试将其传递给标题

fetch('http://localhost:3000/course', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2023-03-28
    • 1970-01-01
    • 2014-05-06
    • 2015-06-27
    • 2020-06-06
    • 2021-02-01
    相关资源
    最近更新 更多