Warm tip: This article is reproduced from serverfault.com, please click

Get POST request body with express and fetch

发布于 2020-12-01 01:56:48

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?

Questioner
Alex Coleman
Viewed
0
Harshana Serasinghe 2020-12-01 10:05:15

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);
});