简体   繁体   English

带有NodeJS GET请求的AngularJS失败-“ Access-Control-Allow-Headers不允许Access-Control-Allow-Header”

[英]AngularJS with NodeJS GET request fails - “Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers”

I've been looking around for some similar questions in search of an answer but I can't find it. 我一直在寻找一些类似的问题,以寻找答案,但找不到。 I have a node.js server with express: 我有一个具有express的node.js服务器:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Headers");
  next();
});

app.use(express.static(__dirname+'/assets'));
app.use(bodyParser.json());

app.get('/', function(req, res, next) {
  res.sendFile(__dirname + '/public/index.html');
});

And AngularJS working with GET requests to a REST API. AngularJS可以处理对REST API的GET请求。 They're triggered by keyup events in a searchform. 它们是由searchform中的keyup事件触发的。 The app.config: app.config:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'Authorization, Access-Control-Allow-Headers';
  $httpProvider.interceptors.push('TokenInterceptor');
});

... And the request code itself: ...以及请求代码本身:

$scope.requestMovies = function() {
    $http.get('http://www.omdbapi.com/?s=' + $scope.titleToSearch +
     '&type=movie&r=json')
    .success(function(data, status, headers, config) {
      $scope.movies = data.Search;
    })
    .error(function(data, status, headers, config) {
      alert("No movie found");
    });
  };

This worked fine until I added authentication to my project (hence the interceptor), and since then I invariably get an error message 在我向项目添加身份验证(因此是拦截器)之前,此方法一直很好,并且此后我总是收到错误消息
XMLHttpRequest cannot load http://www.omdbapi.com/?s=darkmovie&type=movie&r=json. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers.
even though I DID authorize the headers both in the front and back end. 即使我DID授权前端和后端的标头。 Same thing happens in Firefox as it does in Chrome. Firefox中的情况与Chrome中相同。 What am I doing wrong? 我究竟做错了什么?

UPDATE UPDATE

Forgot to post my TokenInterceptor service: 忘记发布我的TokenInterceptor服务:

app.service('TokenInterceptor', function($q, $window, $location, AuthenticationService) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },

    requestError: function(rejection) {
      return $q.reject(rejection);
    },

    /* Set Authentication.isAuthenticated to true if 200 received */
    response: function (response) {
      if (response !== null && response.status == 200 && $window.sessionStorage.token && !AuthenticationService.isAuthenticated) {
        AuthenticationService.isAuthenticated = true;    
      }
      return response || $q.when(response);
    },

    /* Revoke client authentication if 401 is received */
    responseError: function(rejection) {
      if (rejection !== null && rejection.status === 401 && ($window.sessionStorage.token || AuthenticationService.isAuthenticated)) {
        delete $window.sessionStorage.token;
        AuthenticationService.isAuthenticated = false;
        $location.path("/");
      }

      return $q.reject(rejection);
    }
  };
});

Although I still fail to see what's wrong. 虽然我仍然看不到有什么问题。 This was suppose to be a way to check for the authorization token sent from the server everytime an angular view changed. 假定这是每次角度视图更改时检查从服务器发送的授权令牌的一种方法。

将最后一个更改为

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

I was delegating ALL requests to an EXTERNAL API to the CLIENT . 我将所有EXTERNAL API的请求委托给CLIENT I should have figured that this was terrible (and apparently impossible). 我应该已经意识到这是可怕的(显然是不可能的)。 But since it worked the first time (and I have no idea how or why) I kept my architecture like that. 但是由于它是第一次工作(我不知道如何或为什么),所以我保持了这样的架构。 So now basically what I do is: 所以现在基本上我要做的是:

The client now POSTS the URL parameter to the server: 客户端现在将URL参数发布到服务器:

$scope.requestMovies = function() {
    $http.post('/requestMovies', {title: $scope.titleToSearch})
    .success(function(data, status, headers, config) {
      console.log(data.Search);
      $scope.movies = data.Search;
    })
    .error(function(data, status, headers, config) {
      alert("No movie found");
    });
  };



Which handles the GET request for it using a handy node package : 使用方便的节点包处理GET请求:

var Client = require('node-rest-client').Client;
var client = new Client();
//(...)

app.post('/requestMovies', function(req, res, next) {

  client.get('http://www.omdbapi.com/?s=' + req.body.title + '&type=movie&r=json', function(data, response){
    console.log('CLIENT RESPONSE DATA :' + data);
    res.send(data);
  });

});

And of course, the server has any permission to do any kind of requests. 当然,服务器有权执行任何类型的请求。 I hope this helps anyone out there. 我希望这可以帮助任何人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 请求标头字段Access-Control-Allow-Headers在预检响应中不允许使用Access-Control-Allow-Headers - Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response Access-Control-Allow-Headers 不允许请求头字段 Access-Control-Allow-Headers - Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers 预检响应中的 Access-Control-Allow-Headers 不允许 Angularjs 请求标头字段 Access-Control-Allow-Headers - Angularjs Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response Access-Control-Allow-Header不允许授权 - Authorization is not allowed by Access-Control-Allow-Headers NodeJS + ExpressJS:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 - NodeJS + ExpressJS: Request header field not allowed by Access-Control-Allow-Headers in preflight response Access-Control-Allow-Headers AngularJS不允许请求标头字段Content-Type - Request header field Content-Type is not allowed by Access-Control-Allow-Headers AngularJS Safari的XMLHttpRequest(POST)失败,“ Access-Control-Allow-Headers不允许请求标头字段Content-Type” - Safari fails XMLHttpRequest (POST) with ' Request header field Content-Type is not allowed by Access-Control-Allow-Headers' Access-Control-Allow-Headers不允许使用X-Requested-With - X-Requested-With is not allowed by Access-Control-Allow-Headers 飞行前响应中的Access-Control-Allow-Headers不允许请求标头字段Access-Control-Request-Methods - Request header field Access-Control-Request-Methods is not allowed by Access-Control-Allow-Headers in preflight response 预检响应中的Access-Control-Allow-Headers - Access-Control-Allow-Headers in preflight response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM