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

标签 javascript ajax nginx jwt preflight

https://example.com触发 ajax 预请求(发送前)至 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 不允许请求 header 字段授权。

最佳答案

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;
    }
}

关于javascript - 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段授权。 (nginx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093027/

相关文章:

javascript - jQuery 解除绑定(bind)后如何绑定(bind)?

javascript - 如何使用 href 在选项卡之间切换?

html - JQuery: 'Uncaught TypeError: Illegal invocation' 在 ajax 请求 - 几个元素

javascript - 使用 ajax 渲染来自 wikipedia api 的图像

elasticsearch - filebeats 的 Nginx 模块不解析访问日志

javascript - 当用户单击按钮时用 json 填充数组

javascript - 如何使用循环连接 socket.io 客户端

javascript - 从 $.(ajax) 获取单选按钮值并将其传递到 SQL 查询中

ubuntu - 如何与 Flask 后端 api 一起构建 Angular 2 前端应用程序?

linux - SSL 的 Nginx 配置