// axios配置
axios.defaults.withCredentials = true; // 攜帶cookie
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; // 判斷是否爲ajax請求
複製代碼
// 調用代碼
import http from '../utils/request'
export const getInfo = () => {
return http.get('/getInfo')
}
複製代碼
http.HandleFunc("/getInfo", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Add("Access-Control-Allow-Origin", "http://localhost:8080")
writer.Header().Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
writer.Header().Set("Access-Control-Allow-Headers","X-Requested-With")
writer.Header().Add("Access-Control-Allow-Credentials", "true")
for _, item := range common.GetMovies() {
//err := binary.Write(buf, binary.LittleEndian, item)
//if err != nil {
// fmt.Printf("%s", err)
//}
// buf.Bytes()
writer.Write([]byte(item.Title+"\n"))
}
})
http.ListenAndServe("127.0.0.1:8081", nil)
複製代碼
(一) 當前端配置
withCredentials=true
時, 後端配置Access-Control-Allow-Origin
不能爲*
, 必須是相應地址前端(二) 當配置
withCredentials=true
時, 後端需配置Access-Control-Allow-Credentials
ios(三) 當前端配置請求頭時, 後端須要配置
Access-Control-Allow-Headers
爲對應的請求頭集合ajax
Access to XMLHttpRequest at 'http://127.0.0.1:8081/getInfo?t=1545900042823' from origin 'http://localhost:8080' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
複製代碼
參照注意(一)axios
Access to XMLHttpRequest at 'http://127.0.0.1:8081/getInfo?t=1545899934853' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
複製代碼
參照注意(二)後端
Access to XMLHttpRequest at 'http://127.0.0.1:8081/getInfo?t=1545898876243' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
複製代碼
參照注意(三)跨域