问题描述
我在此处进行了相当简单的设置,如下面的代码中所述.但我无法让 CORS
工作.我不断收到此错误:
I have fairly simple setup here as described in the code below. But I am not able to get the CORS
to work. I keep getting this error:
XMLHttpRequest 无法加载 http://localhost:3000/signup.回应预检请求未通过访问控制检查:否 'Access-Control-Allow-Origin' 标头存在于请求的资源上.Origin 'http://localhost:8000' 因此不允许访问.这响应的 HTTP 状态代码为 403.
我确定我在这里遗漏了一些简单的东西.
I am sure I am missing something simple here.
这是我的代码:
package main
import (
"log"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"myApp/src/controllers"
)
func main() {
ac := new(controllers.AccountController)
router := mux.NewRouter()
router.HandleFunc("/signup", ac.SignUp).Methods("POST")
router.HandleFunc("/signin", ac.SignIn).Methods("POST")
log.Fatal(http.ListenAndServe(":3000", handlers.CORS()(router)))
}
推荐答案
请阅读 Markus 建议的链接,以及触发 CORS 预检请求的原因.
Please read the link Markus suggested, and also about what triggers CORS pre-flight requests.
飞行前请求:您可能有像 JSON 这样的内容类型,或其他一些触发飞行前请求的自定义标头,您的服务器可能无法处理这些请求.如果您在前端使用常见的 AJAX,请尝试添加这个:https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requested-With
Pre-flight requests: You may have a content type like JSON, or some other custom header that's triggering a pre-flight request, which your server may not be handling. Try adding this one, if you're using the ever-common AJAX in your front-end: https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requested-With
Gorilla 的 handlers.CORS()
将设置合理的默认值以使 CORS 的基础知识为您工作;但是,您可以(也许应该)以更实用的方式进行控制.
Gorilla's handlers.CORS()
will set sane defaults to get the basics of CORS working for you; however, you can (and maybe should) take control in a more functional manner.
// Where ORIGIN_ALLOWED is like `scheme://dns[:port]`, or `*` (insecure)
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
// start server listen
// with error handling
log.Fatal(http.ListenAndServe(":" + os.Getenv("PORT"), handlers.CORS(originsOk, headersOk, methodsOk)(router)))
这篇关于使 golang Gorilla CORS 处理程序工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!