douqiaolong0528 2016-11-15 20:32
浏览 62
已采纳

在使用kami制作的golang服务器中使用CORS

Hello I'm trying to access a GET request on a Golang api running on localhost:8000 from a ReactJS web app running on localhost:3000. But whenever I try to do this, I get the following error:

Fetch API cannot load http://localhost:8000/api/v1/systems.
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 

Here's a snippet of my Go server code:

func main() {
    session, err := mgo.Dial(mongoURI())
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

    systemsC := session.DB("").C("systems")

    flag.Parse()
    ctx := context.Background()
    kami.Context = ctx

    kami.Use("/api/", httpauth.SimpleBasicAuth(os.Getenv("BASIC_USERNAME"), os.Getenv("BASIC_PASSWORD")))

...

    kami.Get("/api/v1/systems", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
        systems := []alpha.System{}
        systemsMap := map[string][]alpha.System{}

        err := systemsC.Find(nil).All(&systems)
        if err != nil {
            log.Println(err.Error())
            http.Error(w, err.Error(), 404)
        }
        systemsMap["systems"] = systems

        err = json.NewEncoder(w).Encode(&systemsMap)
        if err != nil {
            http.Error(w, err.Error(), 500)
        }
        w.Header().Set("Content-Type", "application/json")
    })

    kami.Serve()
}

Here's the ReactJS code I'm using to make the GET request:

componentDidMount() {
    fetch('http://localhost:8000/api/v1/systems') 
    .then(function(response) {
        return response.json()
    }).then(function(data) {
        this.setState({ data }, () => console.log(this.state));
    });
}

The complete URL requires credentials: http://user:password@localhost:8000/api/v1/systems

I've tried adding various headers to my kami.Get function, but keep getting the same error:

w.Header().Set("Access-Control-Allow-Origin", "*") //This header doesn't work when credentials are sent

Also tried these to no avail:

w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

Right now I'm trying to use rs/cors, but not sure on how to add it to my code. Do I only need these 3 lines of code:

mux := http.NewServeMux()
handler := cors.Default().Handler(mux)
http.ListenAndServe(":8080", handler)

Not really sure how to mix mux, kami and cors, any help is appreciated, thank you!

EDIT

Maybe a much simpler question would be if anyone knows how to integrate cors with kami. I think this could fix my problem, just can't figure out how to use them together.

  • 写回答

1条回答 默认 最新

  • dongzhi2332 2016-11-16 16:07
    关注

    I just had to create a cors object and pass its handler as middleware to kami:

    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:3000"},
        AllowCredentials: true,
    })
    
    kami.Use("/api/", c.Handler)
    

    This let's me make requests now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号