[英]Cors issue when rest api application server(express) and Angulars js application running on different port
[英]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,請求將會起作用,但這似乎不是一個真正的解決方案,而是一個笨拙的工作。
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插件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.