1、通過允許跨域訪問實現了跨域請求,但為了使每個請求帶上session信息,我設置了withCredentials ,即:
axios.defaults.withCredentials = true
然后跨域請求時會出現如下問題:
Response to preflight request doesn't pass access control check: 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://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解決方案
Access-Control-Allow-Origin 字段必須指定域名,不能為*
Access-Control-Allow-Credentials為true
2.CORS
同域安全策略CORS(Cross-Origin Resource Sharing)
它要求請求的服務器在響應的報頭(Response Header)添加 Access-Control-Allow-Origin標簽,從而允許此標簽所對應域訪問此服務器的資源,調用此服務器的接口。
缺陷:
默認情況下,跨源請求不提供憑據(cookie、HTTP認證及客戶端SSL證明等),通過將withCredentials屬性設置為true,可以指定某個請求應該發送憑據。如果服務器接收帶憑據的請求,會用下面的HTTP頭部來響應:
1 | Access-Control-Allow-Credentials: true |
如果發送的是帶憑據的請求,但服務器的相應中沒有包含這個頭部,那么瀏覽器就不會把相應交給JavaScript,請求就無法得到結果的數據(瀏覽器得到了,但是我們請求的方法得不到,因為被瀏覽器攔截了),因此在需要傳Cookie等時,服務端的Access-Control-Allow-Origin必須配置具體的具體的域名。並且還需要設置其他的請求頭:
1 2 3 4 |
header('Access-Control-Allow-Origin:http://www.xxx.com'); header('Access-Control-Allow-Credentials: true'); //是否支持cookie跨域 header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); |