Angular 2 http post + Nodejs表达

use*_*435 5 javascript node.js angular

我无法在服务器上获得post params.我将Angular 2 app中的post请求发送到Nodejs express服务器.这是我在Angular 2中的代码:

import { Injectable } from 'angular2/core';                                                                                                    
import { Http } from 'angular2/http';

@Injectable()
export class QueryService {
  static get parameters() {                                                                                                                    
    return [[Http]]                                                                                                            
  }                                                                                                                                            
  constructor(http) {                                                                                                            
    this.http = http;                                                                                                                          
  }
  postApi() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post('http://localhost:3001/post_test', JSON.stringify({"id": 1, "name": "2"}), { headers: headers }).toPromise();
  }                                                                                                                                            
}
Run Code Online (Sandbox Code Playgroud)

在浏览器中,我看到post params被发送,例如在chrome部分"Request Playload"中包含我的帖子数据.在这里我的服务器:

app.js:

var bodyParser = require('body-parser');
app.use(bodyParser.json());                                                                                                                
app.use(bodyParser.urlencoded({extended: true}));                                                                                          
Run Code Online (Sandbox Code Playgroud)

路线/ index.js:

exports.post_test = function(req, res) {
    console.log('post_test ', req.body);
}
Run Code Online (Sandbox Code Playgroud)

输出是"post_test {}"

我无法理解,问题出在哪里.因为我的服务器工作正常,当我使用Angular 1 $ http服务进行帖子查询时.请帮我!

Thi*_*ier 3

您忘记导入该类Headers

import { Injectable } from 'angular2/core';                                                                                                    
import { Http, Headers } from 'angular2/http'; // <----
Run Code Online (Sandbox Code Playgroud)

在这种情况下,标头不会与您的请求一起发送,但不会显示错误。