最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get POST request body with express and fetch - Stack Overflow

programmeradmin2浏览0评论

I'm new to server-side development.

I'm trying to set up a node.js server that can receive posts.

My client-server code sends the post request:

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:

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.

What should I do to receive my POST request body?

I'm new to server-side development.

I'm trying to set up a node.js server that can receive posts.

My client-server code sends the post request:

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:

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.

What should I do to receive my POST request body?

Share Improve this question edited Dec 1, 2020 at 2:20 Alex Coleman asked Dec 1, 2020 at 1:56 Alex ColemanAlex Coleman 6471 gold badge5 silver badges12 bronze badges 1
  • are you using any sort of body-parser in your nodejs - doesn't look like it - something like app.use(express.json()) – Bravo Commented Dec 1, 2020 at 2:00
Add a comment  | 

2 Answers 2

Reset to default 16

Try setting up express.json() inside the app:

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.

发布评论

评论列表(0)

  1. 暂无评论