Open hanyue2019 opened 4 years ago
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
).
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
unlike