Vue 項目中遇到的跨域問題及解決方法


原文:https://www.jb51.net/article/137278.htm

問題描述

前端 vue 框架,跨域問題后台加這段代碼
header("Access-Control-Allow-Origin: *");
加了之后報這個錯:

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'. 
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'.

解決辦法

文章鏈接:CORS: credentials mode is ‘include'

xhrFields: {
 withCredentials: false
},

把 withCredentials: true 改成 withCredentials: false,如果你沒加上面那段代碼當然也不會報這個錯。雖然是解決方法很簡單,但經此發現許多知識沒掌握不得不梳理下。

HTTP 請求方式有許多種,有些請求會觸發 CORS 預檢請求。“需預檢的請求”會使用 OPTIONS 方法發起一個預檢請求到服務器,以獲知服務器是否允許該實際請求。
對於跨域請求瀏覽器一般不會發送身份憑證信息。如果要發送憑證信息,需要設置 XMLHttpRequest 的 withCredentials 屬性為 true:withCredentials: true。此時要求服務器的響應信息中攜帶 Access-Control-Allow-Credentials: true,否則響應內容將不會返回。

跨域請求想要帶上 cookies 必須在請求頭里面加上:

crossDomain: true, 
xhrFields: {
  withCredentials: true
}

又變成文章開頭的問題了,解決辦法:

后台代碼:

Access-Control-Allow-Origin: 'http://www.zrt.local:8080'
Access-Control-Allow-Credentials: true

前端代碼:

crossDomain: true, 
xhrFields: {
  withCredentials: true
}

跟之前一樣就行了。

總結

1.不限定跨域地址,不攜帶身份憑證

.NET CORE

services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder 
                        .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                )
            );

PHP后台代碼:

header("Access-Control-Allow-Origin: *");

前端代碼:

xhrFields: {
 withCredentials: false
},

2.指定授權訪問地址,攜帶身份憑證(帶cookies)

.NET CORE

services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
						.WithOrigins(
							// App:CorsOrigins 在 appsettings.json 中,可配多個地址
							_appConfiguration["App:CorsOrigins"]
							   .Split(",", StringSplitOptions.RemoveEmptyEntries)
								.Select(o => o.RemovePostFix("/"))
								.ToArray()
						) 
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                )
            );

PHP后台代碼:

Access-Control-Allow-Origin: 'http://www.zrt.local:8080'
Access-Control-Allow-Credentials: true

前端代碼:

crossDomain: true, 
xhrFields: {
  withCredentials: true
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM