简体   繁体   中英

Receiving POST data with Express.js sent by angular2 app

I have following code on Node.js:

app.post('/register', function(req, res) {
  console.log(req.body);

But it appears that req object does not have body property.

With angular2 I am sending stringified JSON with Content-Type:application/json

Angular code looks like this:

this.http.post(
  "http://url.com",
  JSON.stringify(data_obj), {headers:{'Content-Type': 
  'application/json'}}).subscribe((res:Response) => this.extractData(res));

Thanks

The NodeJS application does not have bodyParser so it is unable to parse the body of the request. Do this in your NodeJS application

Install body-parser

npm install body-parser --save

Add to nodeJS app

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

You have to use the body parser middleware in your app:

https://github.com/expressjs/body-parser

you can install it with this command: npm install body-parser --save

for example you can write this code to your main file:

let bodyParser = require('body-parser')

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

This is a basic configuration for the body parser middleware, it parse POST parameters into req.body.

If you want to learn more about the configurations of body parser, read the associate doc into the github repo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM