【问题标题】:Angular 2 http post + Nodejs expressAngular 2 http post + Nodejs express
【发布时间】:2016-07-09 21:28:42
【问题描述】:

我无法在服务器上获取帖子参数。我将 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 部分“请求播放负载”中包含我的帖子数据。 这里是我的服务器:

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 服务进行后期查询时。 请帮帮我!

【问题讨论】:

    标签: javascript node.js angular


    【解决方案1】:

    您忘记导入 Headers 类:

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

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

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多