我无法在服务器上获取帖子参数。我在 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/