在不同端口上运行时,rest api应用程序服务器(express)和Angulars js应用程序之间的Cors问题

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

本文关键字:应用程序 Angulars express js 之间 问题 Cors 服务器 运行时 api rest      更新时间:2023-10-29

我们的应用程序建立在解耦的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插件