0

I'm posting some data from my ReactJS client to the Express server, but it seems that I cannot access the data in req.body.... I'm sending a JSON object this way:

var url = 'http://localhost:8000/scrape/';
    const {main} = getState()

    const info = { name : main.title, items : main.list}
    var options = {
      url: url,
      method: 'POST',
      body : JSON.stringify(info),
      json: true,
      headers : {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };


    Request(options, (error, response, data) => {
        // !error ? dispatch( setSearchResults(JSON.parse(data) ) ) : dispatch( setError(error) );
    });

and when I console.log(req.body) in Express, I receive this:

{ '{"name":"test","items":': { '{"url":"test","code":"ING"},{"url":"test","code":"KIN"},{"url":"test","code":"GAO"}': '' } }

In my Express I use bodyParser

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

I tried using JSON.stringify(req.body) and JSON.parse(req.body) but both had not succes, any suggestions?

Laurens Mäkel
  • 815
  • 2
  • 12
  • 29
  • Why do you make the `Content-Type` as `application/x-www-form-urlencoded` while the POST body is JSON? – shaochuancs Aug 26 '17 at 09:02
  • Yeah I noticed that aswell when I looked at the code, seems that when I try application/json the req.body will remain emty in Express – Laurens Mäkel Aug 26 '17 at 09:03
  • What is the `Request` module in the code? Also, have you checked the HTTP network in the Browser DevTool -- is the JSON body sent from client when `Content-Type` is `application/json`? – shaochuancs Aug 26 '17 at 09:07
  • Request is this libary https://www.npmjs.com/package/request , when Content-Type is application/json the request will be sent as an OPTIONS request and doesn't even reach my express server – Laurens Mäkel Aug 26 '17 at 09:11
  • body parsers doesn't chain, only one can run per request. in this case it seems like the `urlencoded` kicks in and parses the body which is a string so i guess `req.body` is a string. bottom line: use JSON content type – MrBar Aug 26 '17 at 09:12
  • As I said in a previous comment, JSON content type is not reaching the server because it's sent as a OPTIONS request? – Laurens Mäkel Aug 26 '17 at 09:16

1 Answers1

0

This was the solution: How to allow CORS?

And this is how I make a correct JSON request:

var options = {
      uri: url,
      method: 'POST',
      json: {
        "name": main.tile, "items" : main.list
      }
    };

    Request(options, (error, response, data) => {

    });
Laurens Mäkel
  • 815
  • 2
  • 12
  • 29