繁体   English   中英

Angular 2 http post + Nodejs表达

[英]Angular 2 http post + Nodejs express

我无法在服务器上获得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();
  }                                                                                                                                            
}

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

app.js:

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

路线/ index.js:

exports.post_test = function(req, res) {
    console.log('post_test ', req.body);
}

输出是“post_test {}”

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

您忘记导入Headers类:

import { Injectable } from 'angular2/core';                                                                                                    
import { Http, Headers } from 'angular2/http'; // <----

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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