如何解决Go CORS 问题没有响应
我有一个使用 fetch 调用 go mux api 的 React 应用程序。
我很清楚这里的问题:Making golang Gorilla CORS handler work
但这对我不起作用。我已经尝试了该帖子中的所有内容,但仍然没有成功。看起来 go 甚至没有为我运行任何中间件或路由处理函数。
这是我尝试修复它的第一种方法。这使用 gorilla/handlers
package main
import (
"fmt"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func commonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
fmt.Println("MIDDLEWARE CALLED")
w.Header().Set("Access-Control-Allow-Origin","*")
w.Header().Set("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE")
w.Header().Set("Access-Control-Allow-Headers","Accept,Content-Type,Content-Length,Accept-Encoding,X-CSRF-Token,Authorization")
next.ServeHTTP(w,r)
})
}
func ApiHandler(w http.ResponseWriter,r *http.Request) {
fmt.Println("ROUTE CALLED")
fmt.Fprintf(w,`{"works:"true}`)
}
func main() {
var router *mux.Router = mux.NewRouter()
router.Use(commonMiddleware)
router.HandleFunc("/api",ApiHandler).Methods("POST")
headersOk := handlers.AllowedHeaders([]string{"Access-Control-Allow-Origin","Accept","Accept-Language","Content-Type","Content-Language","Origin"})
originsOk := handlers.AllowedOrigins([]string{"http://localhost:*","*"})
methodsOk := handlers.AllowedMethods([]string{"GET","HEAD","POST","PUT","OPTIONS"})
http.ListenAndServe(":8000",handlers.CORS(headersOk,originsOk,methodsOk)(router))
}
这使用 rs/cors
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
func commonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
fmt.Println("MIDDLEWARE CALLED")
w.Header().Set("Access-Control-Allow-Origin",ApiHandler).Methods("POST")
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},AllowCredentials: true,})
handler := c.Handler(router)
http.ListenAndServe(":8000",handler)
}
然而,在这两种情况下,浏览器中仍会出现 CORS 错误。我在端口 5000 上运行 react 服务器,而 go 服务器在端口 8000 上。
fetch("http://localhost:8000/api",{
method: 'POST',headers: {
// "Access-Control-Allow-Origin": "*",'Content-Type': 'application/json'
},body: JSON.stringify({
example: 1
})
})
Chrome 中的错误:
Access to fetch at 'http://localhost:8000/validate/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
这两种解决方案都不起作用。实际上“MIDDLEWARE CALLED”和“ROUTE CALLED”在go中永远不会打印出来。 api 在 Postman 中工作得很好,所以我知道路由器工作正常,问题确实是 CORS。所以看起来这条路线永远不会被调用。
这太棒了,它是否与预检有关。如何禁用所有 cors 问题?
解决方法
如果您想允许所有来源,另一种方法是
c := cors.New(cors.Options{
AllowOriginFunc: func(r string) bool {
return true
}
})
,
我遇到了类似的问题。问题出在我的防病毒软件中。禁用它可以解决问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。