【问题标题】:Get POST request body with express and fetch使用 express 和 fetch 获取 POST 请求正文
【发布时间】:2020-12-01 10:20:05
【问题描述】:

我是服务器端开发的新手。

我正在尝试设置一个可以接收帖子的 node.js 服务器。

我的客户端-服务器代码发送 post 请求:

function post(){
  fetch('/clicked', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Text'})
  })
    .then(function(response){
      if(response.ok){
        console.log('POST success.');
        return;
      }
      throw new Error('POST failed.');
    })
    .catch(function(error){
      console.log(error);
    });
}

我的 Node.js 服务器接收到它:

const express = require('express');
const app = express();
app.use(express.json());
app.post('/clicked', (req, res) => {
  console.log(req.a);
  console.log(req.b);
  console.log(req.body);
  res.sendStatus(201);
})

但是,我的服务器控制台记录了所有 undefined

我应该怎么做才能收到我的 POST 请求正文?

【问题讨论】:

  • 你是否在你的 nodejs 中使用了任何类型的 body-parser - 看起来不像 - 类似于 app.use(express.json())

标签: javascript node.js http post


【解决方案1】:

尝试在应用内设置express.json()

const express = require('express');
const app = express();
app.use(express.json()) 

app.post('/clicked', (req, res) => {
  console.log(req.a);
  console.log(req.b);
  console.log(req.body);
  res.sendStatus(201);
});

【讨论】:

    【解决方案2】:

    在处理发布请求之前添加它。

    app.use(require('body-parser').json());
    

    body-parser 所做的是,它将我们传递给 API 的所有信息添加到 'request.body' 对象中。

    【讨论】:

    • 请注意,这也需要安装中间件,例如npm install body-parser
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2015-02-18
    • 2023-04-10
    相关资源
    最近更新 更多