如何从请求中删除授权 header

How to remove authorization header from request

我正在使用 MEAN Stack User Registration and Login Example & Tutorial 作为我的应用程序的基础。它向 运行 函数中的每个请求添加一个 auth header:

$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;

我想将图片上传到 Cloudinary,但出现此错误:

XMLHttpRequest cannot load https://api.cloudinary.com/v1_1/xxxx/upload. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

我如何删除这个 header 专门针对 Cloudinary 的请求?

这个问题之前有人问过。答案可见.

When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS verb and includes several headers, one of which being Access-Control-Request-Headers listing the headers the client wants to include in the request.

You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).

您将需要一个拦截器来检查请求的 url 并在匹配时清除 header。或者,您可以使用 $http 配置参数。

使用参数:

$http.post('https://api.cloudinary.com/v1_1/' + someId + '/upload', data, { headers: {} });

使用拦截器:

.factory('cloudinaryInterceptor', function() {
 return {
  request: function(config){
   var authHeader = config.headers('authorization');
   //Check for the host
   var regex = /api\.cloudinary\.com/i;
   if(regex.test(config.url))
    //Detach the header
    delete config.headers.authorization;
   return config;
  }
 }
});

记得在配置阶段推送拦截器

$httpProvider.interceptors.push('cloudinaryInterceptor');