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/