【问题标题】:Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response. (nginx)预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权。 (nginx)
【发布时间】:2017-10-20 22:34:06
【问题描述】:

https://example.com 触发 ajax 预请求(beforeSend)到https://api.example.com(nginx)

$.ajax({
    method: "POST",
    url: 'https://api.example.com',
    xhrFields: {withCredentials: true},
    data: {...},
    success: function(msg) {...},
    beforeSend: function(request){
        var token = 'xxxxxx';
        request.setRequestHeader('Authorization', 'Bearer ' + token);
    },
    complete: function(msg) {},
    error: function(xhr, ajaxOptions, thrownError) {}
});

Chrome 控制台返回错误信息

XMLHttpRequest 无法加载 https://api.example.com/auth。预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权。

【问题讨论】:

    标签: javascript ajax nginx jwt preflight


    【解决方案1】:
    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin "https://example.com";
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization";
            add_header Access-Control-Allow-Credentials "true";
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }
    }
    

    【讨论】:

    • 这是一个解决方案吗?只是想知道,因为没有解释这是什么或这段代码属于哪里
    • 上面发布的解决方案对我有用,这需要添加到可疑服务器的/etc/nginx/sites-available/default中。
    【解决方案2】:

    我将它添加到 Nginx 并且它有效:

    add_header Access-Control-Allow-Headers "Authorization";
    

    对于错误:

    请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'https://localhost:3000' 因此不允许访问。

    我在 Nginx 中添加了这个:

    add_header Access-Control-Allow-Origin *;
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2016-05-15
      • 2017-10-28
      • 2017-10-15
      • 1970-01-01
      • 2016-04-24
      • 2019-02-21
      • 2017-06-23
      相关资源
      最近更新 更多