使Golang Gorilla Cors处理程序工作



我在此处具有相当简单的设置,如下所述。但是我无法让CORS工作。我一直遇到此错误:

xmlhttprequest无法加载http://localhost:3000/igep。响应 前飞行请求不通过访问控制检查:否'访问 - 请求的资源中存在控制允许孔的标头。 因此,不允许访问原点" http://localhost:8000"。这 响应具有HTTP状态代码403。

我确定我在这里缺少一些简单的东西。

这是我拥有的代码:

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)))
}

请阅读所建议的链接标记,以及有关触发飞行前请求的内容。

前飞行请求:您可能具有诸如JSON之类的内容类型,或其他一些触发前飞行请求的自定义标题,您的服务器可能无法处理。如果您在前端中使用了Ever-common Ajax,请尝试添加此内容:https://en.wikipedia.org/wiki/wiki/list_of_http_header_header_fields#requested with

大猩猩的handlers.CORS()将设置理智的默认设置,以使CORS的基础知识为您工作;但是,您可以(也许应该)以更具功能的方式控制。

这是一些入门代码:

// 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)))

您可以在此处获取更多详细信息:为什么邮递员没有在请求的资源上出现"不访问'access-control-allow-hall-origin'标题。当我的JavaScript代码执行时错误?关于这个问题。

还尝试此处理程序:Go Cors处理程序,该处理程序应该解决您的问题。我发现这个问题更干净,很容易解决问题。

package main
import (
    "log"
    "net/http"
    "github.com/rs/cors"
    "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")
    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:8000"},
        AllowCredentials: true,
    })
    handler := c.Handler(router)
    log.Fatal(http.ListenAndServe(":3000", handler)
}

您应该创建一个CORSOption对象。例如,要允许任何来源,请使用此代码:

corsObj:=handlers.AllowedOrigins([]string{"*"})

然后,将此对象传递到handle.CORS函数:

log.Fatal(http.ListenAndServe(":3000", handlers.CORS(corsObj)(router)))

用于测试它您可以使用卷曲:

curl -H "Origin: http://example.com" 
-H "Access-Control-Request-Method: POST" 
-H "Access-Control-Request-Headers: X-Requested-With" 
-X OPTIONS --verbose http://127.0.0.1:3000

工作时,您应该看到这些标题:

> Accept: */*
> Origin: http://example.com
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: X-Requested-With

最终代码在这里:https://play.golang.org/p/aorljswhvf

更多信息:

  • 允许的元素功能
  • 如何用卷发调试CORS请求?

我意识到这是一个古老的问题,但是我花了30分钟才能正确。

handler = handlers.CORS(
    // handlers.AllowedMethods([]string{"GET", "POST", "PUT"}),
    handlers.AllowedHeaders([]string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin"}),
    // handlers.AllowedOrigins([]string{"*"}),
)(handler)

要注意的事情:

  • 允许的方法不需要明确包含OPTIONS,这是CORS处理程序的一部分
  • 需要明确提及允许的人,*不是有效的通配符。典型的Ajax库将在请求application/json之类的内容时发送Content-Type,因此请添加。
  • *是允许果蛋白的默认值

声明MUX对象后,将AccessControlmiddleware作为中间件添加到声明的对象。

func main(){
  ac := new(controllers.AccountController)
    router := mux.NewRouter()
    router.Use(accessControlMiddleware)
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")
    http.ListenAndServe(":3000", corsOpts.Handler(router))
}
// access control and  CORS middleware
func accessControlMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Access-Control-Allow-Origin", "*")
            w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS,PUT")
            w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
                if r.Method == "OPTIONS" {
                    return
                }
                next.ServeHTTP(w, r)
            })
        }
package main
import (
    "log"
    "net/http"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
       "github.com/rs/cors"
)
func main() {
     ac := new(controllers.AccountController)
    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")
//cors optionsGoes Below
corsOpts := cors.New(cors.Options{
    AllowedOrigins: []string{"http://localhost:8100"}, //you service is available and allowed for this base url 
    AllowedMethods: []string{
        http.MethodGet,//http methods for your app
        http.MethodPost,
        http.MethodPut,
        http.MethodPatch,
        http.MethodDelete,
        http.MethodOptions,
        http.MethodHead,
    },
    AllowedHeaders: []string{
        "*",//or you can your header key values which you are using in your application
    },
})
    http.ListenAndServe(":3000", corsOpts.Handler(router))
}

基于耶利米的答案。

CORS过滤器设置在服务器端。请求可能与Postman一起使用,并且可以使用浏览器失败,因为Postman没有发送前闪烁请求,而浏览器则是。

设置CORS过滤器将允许您配置后端接受的原始,方法和标题。

此外,如果您的浏览器发射或放置包含JSON有效载荷的请求(这是相当有理的),则需要将'Content-Type'添加到允许的标题中。

最后,handlers.CORS()(router)不仅可以与http.ListenAndServe功能一起使用,而且还可以与http.Handle()一起使用。

代码的片段看起来像:

router := mux.NewRouter()
// do all your routes declaration
headersOK := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOK := handlers.AllowedOrigins([]string{"*"})
methodsOK := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS", "DELETE", "PUT"})
http.Handle("/", handlers.CombinedLoggingHandler(os.Stderr, handlers.CORS(headersOK, originsOK, methodsOK)(router)))

值得一提的是,我成功地使用了Google Cloud Platform标准Appengine中使用此代码段(我相信它也可以在Appengine中使用)。

上述软件包github.com/rs/cors提供构造函数

AllowAll() *Cors

那个

...创建一个具有宽松配置的新CORS处理程序,允许所有与所有标题和凭据一起使用的所有标准方法的起源。

相关内容

最新更新