将自定义标头添加到jquery ajax GET中会导致CORS错误

时间:2018-08-06 20:48:30

标签: jquery ajax asp.net-core cors

我有一个.net核心站点托管在具有以下CORS配置的azure服务结构中:

在ConfigureServices中:

services.AddCors(options =>
{
    options.AddPolicy("AllowAllPolicy", builder =>
    {
        builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

请注意,此配置只是为了查看它是否有效。但是,我尝试添加所添加的特定来源,方法和标头,但似乎没有什么不同。

在“配置”中:

app.UseCors("AllowAllPolicy");

这与Controller动作有关:

[EnableCors("AllowAllPolicy")]

当前通过简单的jquery ajax调用进行调用:

jQuery.ajax({
type: 'GET',
dataType: 'json',
url: url,
crossDomain: true, 
data: {
    'id' : id
},
beforeSend: function(jqXhr, settings) {
    if(access_token !== null) {
        jqXhr.setRequestHeader("Token", + access_token);
    }
    if(deviceHash !== null) {
        jqXhr.setRequestHeader("DeviceId", deviceHash);
    }
},
success: function(data){

},
error : function(jqXHR, textStatus, errorThrown) {

}
});

根据规范,这显然会触发预检请求。没关系,但是我在Chrome中遇到了几个错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Cross-Origin Read Blocking (CORB) blocked cross-origin response [...] with MIME type application/json.

在我尝试在AJAX调用中添加自定义标头之前,请求运行正常。

0 个答案:

没有答案