我在angular.js APP和express.js REST之间进行通信时遇到问题。
我正在将yeoman 1.0与生成器角度0.7.1一起使用。
我尝试为我使用中间件配置,grunt serve
但没有使它正常工作。
Angular App(端口:9000):
angular.module('wboxApp')
.controller('AdminCtrl', function ($scope, $routeParams, $http, fbRef) {
var ref = fbRef();
var token = $routeParams.token;
$http.post('http://127.0.0.1:3000/box/token/get', {token: token}).success(function (data) {
console.log(data);
}
});
});
Express API(端口:3000):
app.post('/box/token/get', function (req, res) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
var token = req.body.token;
var tokenRef = ref.child('tokens').child(token);
tokenRef.once('value', function (data) {
var fullToken = data.val();
fullToken = fullToken + '.' + token;
if (data.val()) {
res.json({fullToken: fullToken});
} else {
res.json({fullToken: null});
}
});
});
浏览器错误:
OPTIONS http://127.0.0.1:3000/box/token/get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:9000' is therefore not allowed access.
XMLHttpRequest cannot load http://127.0.0.1:3000/box/token/get. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:9000' is therefore not allowed access.
似乎该角度页面由运行在127.0.0.1:9000上的服务器提供服务。跨源策略禁止来自其他域的ajax请求。为了解决这个问题,您可以添加快速中间件,该中间件添加跨源请求的标头-
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
next();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句