CORS跨域

CORS跨域

前端代碼模塊

// 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-Credentialsios

(三) 當前端配置請求頭時, 後端須要配置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.
複製代碼

參照注意(三)跨域


不足之處請多指教~

相關文章
相關標籤/搜索