ceb*_*bor 2 rest node.js express angularjs yeoman
我的angular.js APP和我的express.js REST之间的沟通有问题.
我正在使用具有发电机角度0.7.1的yeoman 1.0.
我尝试使用中间件配置,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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
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});
}
});
});
Run Code Online (Sandbox Code Playgroud)
浏览器错误:
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.
Run Code Online (Sandbox Code Playgroud)
似乎角度页面由运行在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();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5322 次 |
| 最近记录: |