本文介绍了Angular 2 http post + Nodejs表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't get post params on the server. I send post request in Angular 2 app to Nodejs express server.Here my code in 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是send,例如在chrome部分Request Playload包含我的帖子数据。
这里我的服务器:

In the browser I see that post params was send, for example in chrome section "Request Playload" contains my post data.And here my server:

app.js:

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

routes / index.js:

routes/index.js:

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

,输出为post_test {}

and the output is "post_test {}"

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

I can't understand, where is the problem. Because my server works fine, when I used Angular 1 $http service for post queries.Please, help me!

推荐答案

您忘记导入标题 class:

You forgot to import the Headers class:

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

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

In this case, the headers aren't sent along with your request but no error is displayed.

这篇关于Angular 2 http post + Nodejs表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:06