javascript - Angular 2 http post + Nodejs express

标签 javascript node.js angular

我无法在服务器上获取帖子参数。我在 Angular 2 应用程序中将发布请求发送到 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();
  }                                                                                                                                            
}

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

应用程序.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'; // <----

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

关于javascript - Angular 2 http post + Nodejs express ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163787/

相关文章:

javascript 在音频中添加 onend 事件

javascript - 为什么只有一小部分这个 div 可见?

javascript - jQuery : Replace all unformatted text outside of html tags with multiple dropdown boxes

angular - 如何在 Angular 2(路由器 3)中处理租户子域

angular - 如何将 Bootstrap 添加到 angular-cli 项目

javascript - 如何在 socket.io 服务器中调用 Node api 响应

javascript - 打印到控制台时为 NaN 但 typeof 为数字 jquery

mysql - Sequelize : not able to login via localhost?

javascript - 在 node.js 中,为什么会有一个 util.isArray 和一个 Array.isArray?

node.js - Mongoose 查找查询传递变量