Lucas
Lucas

Reputation: 57

Posting json data from angular to nodejs

How to post json data from angular to nodejs server.

Tried to change the header to multipart/form-data but received data with the entire object as key of received data and the 'plus' characters were replaced by space.

//Service
const httpOptions = {
   headers: new HttpHeaders({
  'Content-Type': 'application/json'
   })
};


public post(data){
  return this.http.post('http://localhost:3000/', data, httpOptions);
}

//Component
.post({'ok++':'++'}).subscribe(
        (data:any) => { }

//nodejs server
var http = require('http');
var qs = require('querystring');

http.createServer(function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    var body = '';

    request.on('data', function (data) {        
        body += data;
    });

    request.on('end', function () {
        var data = qs.parse(body);
        console.log(data);
    });
}).listen(3000, function () { });

with header 'Content-Type': 'application/json' expected: {'ok++':'++'}

received: [Object: null prototype] {}

with header 'multipart/form-data' expected: {'ok++':'++'}

received: [Object: null prototype] { '{"ok ":" "}': '' }

Upvotes: 0

Views: 468

Answers (2)

Lucas
Lucas

Reputation: 57

With header 'multipart/form-data' and as the braza's answer says, using JSON.parse() instead of qs.parse() on nodejs server the expected result is reached.

Upvotes: 0

braza
braza

Reputation: 4662

I don't think you want to use qs.parse here, as that is trying to parse a query string. What you are posting is a JSON request.

Try changing qs.parse to JSON.parse (no import necessary)

request.on('end', function () {
    // `JSON` instead of `qs`
    var data = JSON.parse(body);
    console.log(data);
});

Upvotes: 1

Related Questions