我在一台服务器上设置了nodeJS,而我的AngularJS设置在另一台服务器上。我试图将我的AngularJS数据发布到NodeJS作为测试,并让它反弹回来。但每当我检查我的NodeJS中的req.body时,它总是空的。这是Nodejs中的代码:
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');
var app = express();
app.use(logfmt.requestLogger());
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
app.post('/', function(req, res, next) {
res.send(req.body);
});
无论我从AngularJS应用程序发送什么,req.body总是返回空。以下是我的AngularJS中相应代码的片段:
var tempdata = { "test": "testing" };
$scope.searchnow = function () {
$http.post("http://afternoon-savannah-3595.herokuapp.com/", tempdata)
.success(function (data) {
console.log(data);
}).error(function () {
console.log("something went wrong");
})
}
任何帮助都将不胜感激。
答案 0 :(得分:1)
您需要安装并使用body-parser
才能实现此功能:
npm install --save body-parser
并在app.js中(我也将你的监听电话移到了文件的底部)
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');
var bodyparser = require('body-parser');
var app = express();
app.use(logfmt.requestLogger());
app.use(bodyparser());
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
app.post('/', function(req, res, next) {
res.send(req.body);
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});