[英]Cors issue while accessing golang iris framework rest calls in frontend
我正在使用 golang iris 框架通过休息调用添加用户。 这是我的代码
package main
import (
"fmt"
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
)
type User struct {
Name string
}
func main() {
app := iris.New()
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
AllowCredentials: true,
})
app.Use(crs)
//
app.Post("/send", func(ctx iris.Context) {
// deployment Object
name := User{}
ctx.ReadJSON(&name)
fmt.Println(name)
})
app.Run(iris.Addr("localhost:8080"))
}
它工作正常。 但是我在前面的 ajax 调用中遇到了 cors 错误。 我添加了 cors 选项。 但我仍然收到以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the
remote resource at http://localhost:8080/send. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). (unknown)
我找不到错误是什么。 请任何人帮助解决这个问题。
提前致谢。
您必须使用.AllowMethods(iris.MethodOptions)
函数为您的Party/Group
或整个应用程序允许OPTIONS
HTTP 方法。 https://github.com/kataras/iris/blob/master/_examples/experimental-handlers/cors/simple/main.go示例已经向您展示了方式。
package main
import (
"fmt"
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris/v12"
)
type User struct {
Name string
}
func main() {
app := iris.New()
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
AllowCredentials: true,
})
app.Use(crs)
//
app.AllowMethods(iris.MethodOptions) // <- HERE
app.Post("/send", func(ctx iris.Context) {
// deployment Object
name := User{}
ctx.ReadJSON(&name)
fmt.Println(name)
})
app.Run(iris.Addr(":8080"))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.