解决前端调用后端跨域问题
# 解决前端调用后端跨域问题
CORS 是浏览器执行的跨源访问策略。服务端应维护明确的允许来源列表,并正确响应预检请求。
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") == "https://app.example.com" {
w.Header().Set("Access-Control-Allow-Origin", "https://app.example.com")
w.Header().Set("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
携带 Cookie 或 Authorization 时不能把允许来源简单设为 *。CORS 不是身份认证,也不能阻止服务器之间直接请求;敏感操作仍需要认证、授权和 CSRF 策略。