0

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 ":" "}': '' }

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

With header 'multipart/form-data' it works!, thank you.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.