dongxie8856 2017-04-05 13:20
浏览 497
已采纳

带有golang后端的CORS请求不起作用

I'm facing some issue with my implementation. I have a backend written in Golang and the UI (in Angular2) which are on the same server.

I've tried to set the CORS handling in my backend but it still doesn't work and I'm not getting why.

Here's my code:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/rs/cors"
)

var router *mux.Router

func main() {
    router = mux.NewRouter()

    HandleFuncEx("/authentication", handleAuthentication)
    HandleFuncEx("/callA", handleCallA)
    HandleFuncEx("/callB", handleCallB)
    HandleFuncEx("/callC", handleCallC)

    handler := cors.New(cors.Options{
        AllowedOrigins: []string{"*"},
        AllowedMethods: []string{"GET", "POST", "PATCH"},
        AllowedHeaders: []string{"a_custom_header", "content_type"},
    }).Handler(router)
    http.ListenAndServe(":8000", handler)

}

func HandleFuncEx(pattern string, handler func(http.ResponseWriter, *http.Request)) {
    log.Println("handled function", pattern)
    router.HandleFunc(pattern, handler)
}

The authentication pattern works correctly (is the first called by the UI) all the others calls fails the preflight request. Why is it happening?

Thanks everybody for the help!

EDIT:

This is an example of a non-working response Headers:

HTTP/1.1 200 OK
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Date: Fri, 07 Apr 2017 08:33:12 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

And these are request's headers:

OPTIONS /users HTTP/1.1
Host: /* Removed by my company policy */
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: /* Removed by my company policy */
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Access-Control-Request-Headers: access_token
Accept: */*
Referer: /* Removed by my company policy */
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4,la;q=0.2
  • 写回答

3条回答 默认 最新

  • dtkvlj5386 2017-04-07 09:08
    关注

    As Adrian pointed out, you need to add the OPTIONS Method to the AllowedMethods array.

    Please also consider to add Accept, Accept-Language and Content-Type to the AllowedHeaders as good practice.

    If you don't want to use the github.com/rs/cors package, you can write a simple CORS decorator middleware on your own like this:

    CORS decorator

    import (
        "net/http"
    
        "github.com/gorilla/mux"
    )
    
    // CORSRouterDecorator applies CORS headers to a mux.Router
    type CORSRouterDecorator struct {
        R *mux.Router
    }
    
    // ServeHTTP wraps the HTTP server enabling CORS headers.
    // For more info about CORS, visit https://www.w3.org/TR/cors/
    func (c *CORSRouterDecorator) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
        if origin := req.Header.Get("Origin"); origin != "" {
            rw.Header().Set("Access-Control-Allow-Origin", origin)
            rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
            rw.Header().Set("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Type, YourOwnHeader")
        }
        // Stop here if its Preflighted OPTIONS request
        if req.Method == "OPTIONS" {
            return
        }
    
        c.R.ServeHTTP(rw, req)
    }
    

    HTTP server

    r := mux.NewRouter()
    r.Handle("/authentication", handleAuthentication)
    
    http.Handle("/", &CORSRouterDecorator{r})
    

    et voilà.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题