字数
359 字
阅读时间
2 分钟
前端代码模块
js
// axios配置
axios.defaults.withCredentials = true; // 携带cookie
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; // 判断是否为ajax请求js
// 调用代码
import http from '../utils/request'
export const getInfo = () => {
return http.get('/getInfo')
}后端代码模块
java
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)注意
1、当前端配置 withCredentials=true 时, 后端配置 Access-Control-Allow-Origin 不能为 *, 必须是相应地址
2、当配置 withCredentials=true 时, 后端需配置 Access-Control-Allow-Credentials
3、当前端配置请求头时, 后端需要配置 Access-Control-Allow-Headers 为对应的请求头集合
问题解决手册
参照注意 1
shell
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.参照注意 2
shell
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.参照代码 3
shell
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.