app.use(express.json) doesn't work post request returning an empty object

Viewed 773
const express = require('express');
          app = express();
          PORT = 3030;
    
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    
    app.get("/", (req, res) => {
      res.send('Hello World')
    });
    
    app.post('/', (req, res) => {
      console.log(req.body);
      res.json(req.body)
    })
    
    app.listen(PORT, err => {
      if(err) {
        return console.log('ERROR', err);
      }
    
      console.log(`Listening on port ${PORT}, http://localhost:${PORT}/`)
    });

I'm using Postman to test it here is what I'm using.

I'm using form-data:

{number: 123, new: new}

I've tried using body-parser but it's depreciated.

I'm using express "^4.17.1"

I'm just wondering if it's something local that could be causing the problem because I've looked up a couple of tutorials and they don't have this issue.

postman details

I've also tried making a request using fetch:

let options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      number: '123',
      new: 'new'
    })
  }
  fetch('http://localhost:3030/', options)
    .then(response => response.json())
    .then(data => console.log(data));

all I get back is:

test.html:61 POST http://localhost:3030/ net::ERR_CONNECTION_REFUSED

Uncaught (in promise) TypeError: Failed to fetch

1 Answers

Your postman image shows form-data (which is probably multipart/form-data) as the content-type which is not something that either of your middleware handlers knows about.

express.json() parses JSON content-types like application/json.

express.urlencoded() parses URl encoded content-types like application/x-www-form-urlencoded.

People often use multer for parsing multipart/form-data, but if this data is just simple form data (name/value pairs), then you should encode it as either application/x-www-form-urlencoded or application/json rather then deploy multer. Multer is typically used when you have file uploads and that's when multipart/form-data is a necessary choice.

Related