休息 api 应用程序服务器(快速)和 Angulars js 应用程序之间的 Cors 问题,而 运行 在不同的端口

Cors issue between rest api application server(express) and Angulars js application while running on different ports

我们的应用程序建立在解耦的 MEAN 堆栈架构上。我正在尝试从我的 Angular 前端向我们的后端发出成功的请求。后端肯定是 returns 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

这是我的第一个 Whosebug post,我对 Express 和 MEAN 堆栈比较陌生,所以如果解决方案显而易见,我深表歉意。我做了很多研究,none 的解决方案,我发现已经解决了问题。

两件事:

首先,尝试将 'Access-Control-Allow-Headers' header 更改为:

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

其次,如果仅用于开发目的,我建议使用Chrome CORS Plugin