简体   繁体   English

使用 express 和 fetch 获取 POST 请求正文

[英]Get POST request body with express and fetch

I'm new to server-side development.我是服务器端开发的新手。

I'm trying to set up a node.js server that can receive posts.我正在尝试设置一个可以接收帖子的 node.js 服务器。

My client-server code sends the post request:我的客户端-服务器代码发送 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);
    });
}

And my Node.js server receives it:我的 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);
})

However, my server console logs all undefined .但是,我的服务器控制台记录了所有undefined

What should I do to receive my POST request body?我应该怎么做才能收到我的 POST 请求正文?

Try setting up express.json() inside the app:尝试在应用程序中设置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);
});

Add this before handling post request.在处理发布请求之前添加它。

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

What body-parser does is, it will add all the information we pass to the API to the 'request.body' object. body-parser 所做的是,它将我们传递给 API 的所有信息添加到“request.body”object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM