middleware icon indicating copy to clipboard operation
middleware copied to clipboard

cors should Change the way

Open hanyue2019 opened this issue 5 years ago • 1 comments

I have try the middleware,but it does not work I find an easy way to handle this,maybe you can change I copy from https://studygolang.com/articles/25389

crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowCredentials: true,
	})
app:= iris.New()
app.Use(crs())

unlike

crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowCredentials: true,
	})

	v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)`

hanyue2019 avatar May 27 '20 05:05 hanyue2019

Hello @hanyue2019 , the method you described in the article, is also described at: https://github.com/kataras/iris/blob/8359c9a0f5b0eadfc16ae24f879b477a18a8b9a4/_examples/experimental-handlers/cors/simple/main.go#L8-L21

crs := func(ctx iris.Context) {
	ctx.Header("Access-Control-Allow-Origin", "*")
	ctx.Header("Access-Control-Allow-Credentials", "true")

	if ctx.Method() == iris.MethodOptions {
		ctx.Header("Access-Control-Methods", "POST, PUT, PATCH, DELETE")
		ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
		ctx.Header("Access-Control-Max-Age", "86400")
		ctx.StatusCode(iris.StatusNoContent)
		return
	}

	ctx.Next()
} 

However, you still need to call the AllowMethods(iris.MethodOptions) in the application/or party you want to register the cors: https://github.com/kataras/iris/blob/8359c9a0f5b0eadfc16ae24f879b477a18a8b9a4/_examples/experimental-handlers/cors/simple/main.go#L23

v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.

There is no other way to register this specific middleware because routes are registered per subdomain, method and path, so AllowMethods.

Don't forget that if you need to override the router behavior and register something before the iris router, you can also use the app.WrapRouter and put the cors code there (that way will not require AllowMethods).

kataras avatar Jun 05 '20 18:06 kataras