请求标头字段 不允许授权


Request header field Authorization is not allowed

我的服务器上有一个基于 Laravel的 API。我尝试从AngularJS前端访问此API。不幸的是,出现了此错误。

我必须在何处添加配置以允许授权标头?我试图找到解决方案,但无法解决。

我试图将其插入 Angular 前端的httpd.conf.htaccess中,但不幸的是它不起作用:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

快速回答

如果您的服务器使用的是 Apache,请将以下代码片段添加到 API 各自的 .htaccess 文件中:

<IfModule mod_headers.c>
          Header set Access-Control-Allow-Headers "Authorization"
</IfModule>

更多详情

在上面的代码片段中,我们要求 Apache 允许Authorization标头:

Header set Access-Control-Allow-Headers "Authorization"

您可以在一行中添加多个headers,如下所示,但请记住,建议仅允许应用所需的标头

Header set Access-Control-Allow-Headers "Authorization, X-Requested-With"

旁注

在相关说明中,人们通常需要允许跨源请求(也称为跨源资源共享或 CORS)。以下代码片段允许来自https://example.com源的交叉请求:

Header set Access-Control-Allow-Origin "https://example.com"

或者,您可以使用"*"来允许来自所有源的请求:不推荐

Header set Access-Control-Allow-Origin "*"

<IfModule mod_headers.c>
    # To allow headers
    Header set Access-Control-Allow-Headers "Authorization"
    # to allow cross origin request from https://example.com
    Header set Access-Control-Allow-Origin "https://example.com"
</IfModule>