Ajax跨域請求附帶Cookie/Ajax跨域請求附帶身份憑證

1、跨域請求中默認不帶cookie等驗證憑證html

尤爲對於post請求。ajax

對於ajax請求,其中post,get均可以正常訪問。api

withCredentials: false, // 容許攜帶cookie

若是設置容許帶cookie那麼會遇到一個錯誤:跨域

Failed to load http://pre.api.jmxy.mockuai.c...: 
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Origin '
http://pre.promotion.jmxy.moc...' is therefore not allowed access.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

這個錯誤的意思:cookie

也就是說Access-Control-Allow-Credentials設置爲true 的狀況下Access-Control-Allow-Origin不能設置爲 *post

 

解決方案:ui

後臺響應頭中設置對應的容許的域名。url

 

 

2、Asp.Net Core中跨域處理+附帶Cookie驗證spa

注:登陸後cookie存儲,由客戶端完成,後臺僅驗證有效性。.net

 

1.請求中指定

 withCredentials:true  //支持附帶詳細信息
$.ajax({
    url: apiUrl.getCookie('getone'),
    data: { age: 11 },
    xhrFields: {
        withCredentials:true  //支持附帶詳細信息
    },
    crossDomain:true,//請求偏向外域
    success: function (data) {
        alert(data);
    }
});

 

2.響應中,單獨設置容許的域名

//設置跨域訪問
services.AddCors(options =>
{
    options.AddPolicy("any", builder =>
    {
        builder.WithOrigins("http://www.gongjuji.net/", "http://localhost:8080", "http://localhost:8081", "http://localhost:8082")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
    });
});

 

3、特別說明

1.當前設置僅針對同一個根域名的狀況下,好比:www.gongjuji.net    和  erp.gongjuji.net 這樣。

2.

 

更多:

Asp.Net WebApi 啓用CORS跨域訪問指定多個域名

Cors 跨域Access-Control-Allow-Origin

Ajax跨域請求中的Cookie問題(默認不帶cookie等憑證)

相關文章
相關標籤/搜索