2017-04-11 23 views
1

送我有以下的Node.js的代碼:與Express.js後接收的數據通過angular2應用

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

但看來,REQ對象沒有身體屬性。

隨着angular2我與Content-Type的發送字符串化JSON:應用程序/ JSON

角代碼如下所示:

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

感謝

+3

您是否在快速服務器中安裝了任何中間件?說:express [bodyparser](https://github.com/expressjs/body-parser)? – Gimby

+0

不,節點說這個中間件不再與express捆綁在一起,必須單獨安裝 – Maxim

+1

yea,但是你仍然需要像提到的@Gimby那樣解析body。 –

回答

0

中的NodeJS應用不有bodyParser,所以它無法解析請求的正文。在你的NodeJS應用

安裝體解析器

npm install body-parser --save 

執行此加入的NodeJS應用

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

var app = express() 

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

你必須用身體解析器中間件在您的應用程序:

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

,你可以用這個命令來安裝它:npm install body-parser --save

比如你可以這樣寫代碼到你的主文件:

let bodyParser = require('body-parser') 

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

這是人體解析器中間件的基本配置,其解析POST參數進入req.body。

如果您想了解更多關於body parser的配置信息,請將相關文檔閱讀到github repo中。