0

In my onSubmit function :

    try {
    const config = {
      header: {
        'Content-Type': 'application/json'
      }
    }
    const body = JSON.stringify(newUser);
    console.log(body);
    const res = await axios.post('/api/users', body, config);
    console.log(res.data);
  }catch(err) {
    console.error(err.response.data);
  }

When i submit, my server returns 400 bad request with empty req.body

My network:

    Request header:
    Accept: application/json, text/plain, */*
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9,vi;q=0.8
    Connection: keep-alive
    Content-Length: 55
    Content-Type: application/x-www-form-urlencoded
    Host: localhost:3000
    Origin: http://localhost:3000
    Referer: http://localhost:3000/register
    Sec-Fetch-Mode: cors
    Sec-Fetch-Site: same-origin
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36

Form data:
    {"name":"bad","email":"bad@aa.com","password":"123456"}:

My server got request from react app but req.body shows empty, i tried postman and it worked perfectly. What did I do wrong?

Edit: after using bodyParser with bodyParser.json() I finally got an object from req.body

[Object: null prototype] {                                                                                             
'{"name":"bad","email":"bad@aa.com","password":"123456"}': '' } 

but still bad request. I think this unusual object causes the bad request but still don't know how to fix?

le huy
  • 307
  • 1
  • 4
  • 8
  • Can you post the console.log(body) value – Ajay Ghosh Jan 23 '20 at 04:18
  • Not sure you are using the body-parser or not, see the [link](https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express) will get help – Bilas Sarker Jan 23 '20 at 04:28
  • i use app.use(express.json({extended: false})); and my body: {"name":"bad","email":"bad@aa.com","password":"123456"} – le huy Jan 23 '20 at 05:12

2 Answers2

0

You can add following lines for json parsing in your main server file.

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

For more info : Go to this official docs

Krina Soni
  • 870
  • 6
  • 14
0

If you are using express you need to tell server to parse the incoming json. Like:

let express = require('express');
let app = express();

app.use(express.json());

If you are not using express you can just use the simple JSON Body Parser for that.

Muhammad Zeeshan
  • 4,608
  • 4
  • 15
  • 41