简体   繁体   中英

Cors issue while accessing golang iris framework rest calls in frontend

I am using golang iris framework for adding users through rest calls. This is my code

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"))
}

It is working fine. But I am getting cors error in front ajax calls. I have added cors options. But still I am getting the below error.

    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)

I couldn't find what is the error. Please anyone help to solve this issue.

Thanks in advance.

You have to allow the OPTIONS HTTP Method for your Party/Group or the whole app using the .AllowMethods(iris.MethodOptions) function. The https://github.com/kataras/iris/blob/master/_examples/experimental-handlers/cors/simple/main.go example shows you the way already.

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"))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM