在不同端口上运行时,rest api应用程序服务器(express)和Angulars js应用程序之间的Cors问题
Cors issue between rest api application server(express) and Angulars js application while running on different ports
我们的应用程序建立在解耦的MEAN堆栈架构上。我正试图从我的Angular前端向我们的后端发出成功的请求。后端肯定会返回JSON。但每次我从前端向后端发出请求时,我都会收到:
XMLHttpRequest cannot load http://localhost:9000/recipes/175169. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我在后端有以下设置来接受跨来源请求:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
next();
});
从前端发出的请求是:
recipe.controller('RecipeController', function($scope, $http) {
$scope.loadRecipe = function() {
$http({
url: 'http://localhost:9000/recipes/175169',
method: 'get',
headers: { 'Content-type': 'application/json' }
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log('Error: ' + data)
})
}
如果我运行以下命令来禁用chrome,请求会起作用,但这似乎不是一个真正的解决方案,而是一个jenky的变通办法。
open /Applications/Google' Chrome.app--args --disable-web-security
这是我的第一篇StackOverflow文章,我对Express和MEAN堆栈还比较陌生,所以如果解决方案很明显,我很抱歉。我做了很多研究,但没有一个解决方案能解决这个问题。
两件事:
首先,尝试将"Access Control Allow Headers"标头更改为:
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
第二,如果只是出于开发目的,我建议使用Chrome CORS插件
相关文章:
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- Emberjs应用程序加载在除Index之外的所有路由上
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- angular 1.5应用程序中的导航栏
- 在Web应用程序中使用Highcharts javascript
- angularjs+rails应用程序中未显示模板
- 使用acess代币登录Facebook,并通过网络应用程序离线发布
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 科尔多瓦页面类应用程序中的多个谷歌地图
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- Angularjs-utils高亮过滤器在搜索时破坏应用程序
- 在phonegap应用程序内部重定向不起作用
- 使用谷歌应用程序脚本从工作表中获取值并将其显示在文本框中
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- Node.js正在更改应用程序以使用集群模块
- 在openshift node js应用程序中获取请求
- 在不同端口上运行时,rest api应用程序服务器(express)和Angulars js应用程序之间的Cors问题
- 当 rest api 应用程序服务器(express)和 Angulars js 应用程序在不同的端口上运行时,Cors