会的NodeJS不接受angularjs后 [英] nodejs won't accept post from angularjs
问题描述
我有一个设置的NodeJS了一台服务器上,而我的AngularJS建立在另一个上。我想从我的AngularJS的数据发布到作为的NodeJS测试,并简单地有它弹回来。但每当我检查我里面的NodeJS的req.body,它始终是空的。下面是对的NodeJS code:
I have a nodeJS set up on one server, and my AngularJS set up on another. I'm trying to post data from my AngularJS to the NodeJS as a test, and simply have it bounce back. But whenever I check the req.body inside my NodeJS, it is always empty. Here is the code in 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相应code的片段:
No matter what i send from my AngularJS app, the req.body always returns empty. Here is the snippet of corresponding code in my 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");
})
}
任何帮助将是AP preciated。
Any help would be appreciated.
推荐答案
您需要安装并使用体解析器
这个工作:
You'll need to install and use body-parser
for this to work:
npm install --save body-parser
和在app.js(我也感动你听打电话到文件底部)
and in app.js (I also moved your listen call to the bottom of the file)
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);
});
这篇关于会的NodeJS不接受angularjs后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!