Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cors should Change the way #58

Open
hanyue2019 opened this issue May 27, 2020 · 1 comment
Open

cors should Change the way #58

hanyue2019 opened this issue May 27, 2020 · 1 comment
Labels

Comments

@hanyue2019
Copy link

hanyue2019 commented May 27, 2020

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)`
@kataras
Copy link
Member

kataras commented Jun 5, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants