草庐IT

javascript - CORS 错误 :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

coder 2023-05-28 原文

我正在尝试将请求从一个本地主机端口发送到另一个。我在前端使用 angularjs,在后端使用 Node

由于是CORS请求,在node.js中,我使用的是

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');

在 angular.js 服务文件中,我正在使用

return {
    getValues: $resource(endpoint + '/admin/getvalues', null, {
        'get': {
             method: 'GET',
             headers:{'Authorization':'Bearer'+' '+ $localStorage.token}
             }
     }),
}

我收到以下错误

预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段授权。

请帮忙!

最佳答案

这是一个 API 问题,如果使用 Postman/Fielder 向 API 发送 HTTP 请求,您将不会收到此错误。对于浏览器,出于安全目的,它们总是在发送实际请求(GET/POST/PUT/DELETE)之前向 API 发送 OPTIONS 请求/预检。因此,如果请求方法是OPTION,不仅需要在“Access-Control-Allow-Headers”中添加“Authorization”,还需要在“Access-Control-allow-methods”中添加“OPTIONS”为出色地。我就是这样解决的:

if (context.Request.Method == "OPTIONS")
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
            context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
            context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
            context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

        }

关于javascript - CORS 错误 :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42061727/

有关javascript - CORS 错误 :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response的更多相关文章

随机推荐