因此,我在本地运行后端服务器,并在 localhost:8080 的 Docker 容器中运行前端。当我打开前端时,我得到:
Access to fetch at 'http://localhost:3000/myservice' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我在网上有根,看到了各种版本的设置标题。没有一个起作用。我现在的样子是这样的:
func (m MyService) initializeRoutes() {
m.router.HandleFunc(VERSION+"/stuff", corsHandler(b.getStuff)).Methods("GET")
}
func corsHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Print("preflight detected: ", r.Header)
w.Header().Add("Connection", "keep-alive")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET, DELETE, PUT")
w.Header().Add("Access-Control-Allow-Headers", "content-type")
w.Header().Add("Access-Control-Max-Age", "86400")
// continue with my method
h(w, r)
}
}
func (m MyService) getStuff(w http.ResponseWriter, r *http.Request) {
//Do what is required
}
但是无论我设置什么,我从一开始就会遇到相同的错误。有人知道我为什么会遇到这个问题以及如何解决它吗?
创建中间件:
func EnableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Origin")
w.Header().Add("Vary", "Access-Control-Request-Method")
if r.Header.Get("Origin") != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
if isPreflight(r) {
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, PUT, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.WriteHeader(http.StatusOK)
return
}
break
}
next.ServeHTTP(w, r)
})
}
func isPreflight(r *http.Request) bool {
return r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
}
将中间件包裹在路由器周围:
r := http.NewServeMux()
http.ListenAndServe(":8080", EnableCors(r))
希望有帮助。
编辑2023-06-26:
正如 jub0bs 在评论中推荐的那样,使用 cors 包,其维护方式如下: