[英]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.