1

我正在使用 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)

我找不到是什么错误。请任何人帮助解决这个问题。

提前致谢。

4

1 回答 1

2

您必须允许使用该功能的您或整个应用程序的OPTIONSHTTP 方法。https://github.com/kataras/iris/blob/master/_examples/experimental-handlers/cors/simple/main.go示例已经向您展示了方式。Party/Group.AllowMethods(iris.MethodOptions)

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"))
}
于 2018-10-24T00:18:32.143 回答