CORS跨域

34,437 阅读1分钟

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-Credentials

(三) 当前端配置请求头时, 后端需要配置Access-Control-Allow-Headers为对应的请求头集合

问题解决手册

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.

参照注意(一)

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.

参照注意(三)


不足之处请多指教~