亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用代理中間件的 Echo CORS 會導致使用 Access-Allow-Origins

使用代理中間件的 Echo CORS 會導致使用 Access-Allow-Origins

Go
FFIVE 2023-07-26 20:02:48
我正在使用 LabStack 的 Golang Echo 框架來構建服務。其中一種路由需要代理來自后端服務的請求和響應。但我也需要 CORS 來處理這項服務。所以我在請求/響應堆棧中使用middleware.CORSWithConfigw/a 。middleware.ProxyWithConfig我發現標頭有些奇怪Access-Control-Allow-Origins,其中從代理服務到我的 Echo 服務器的響應中該標頭的值*,但是一旦它通過代理,*, *當它返回客戶端時它就會更改為 。之后我開始看到以下與 CORS 違規相關的瀏覽器錯誤:VM1627:362 Access to XMLHttpRequest at 'http://localhost:6273/' from origin 'http://localhost:8002' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.有人遇到過這個嗎?任何人都知道為什么會發生這種情況以及可能有解決方法嗎?這是一些示例代碼:package mainfunc singleTargetBalancer(url *url.URL) middleware.ProxyBalancer {    targetURL := []*middleware.ProxyTarget{        {            URL: url,        },    }    return middleware.NewRoundRobinBalancer(targetURL)}func Noop(ctx echo.Context) (err error) {    ctx.String(        http.StatusNotImplemented,        "No op handler should never be reached!",    )    return err}func main() {        e := echo.New()    e.HideBanner = true    e.Use(        middleware.CORSWithConfig(middlewares.CustomCorsConfig),        middlewares.ThriftMetrics(),    )        // Have to use a Noop handler since we're not trying to set up a full-on proxy for the backend service.  We only want this one route to be proxied.        e.POST(        "/",        handlers.Noop,        middleware.ProxyWithConfig(middleware.ProxyConfig{             Balancer: singleTargetBalancer("[backend service URL]"),            })    )}
查看完整描述

1 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

我最終通過編寫一個自定義的 Echo 中間件來解決這個問題,以便在 Echo 的代理中間件將標頭發送回客戶端之前掛鉤到響應。


func setResponseACAOHeaderFromRequest (req http.Request, resp echo.Response) {

    resp.Header().Set(echo.HeaderAccessControlAllowOrigin, 

    req.Header.Get(echo.HeaderOrigin))

}


func ACAOHeaderOverwriteMiddleware(next echo.HandlerFunc) echo.HandlerFunc {

    return func(ctx echo.Context) error {

        ctx.Response().Before(func() {

            setResponseACAOHeaderFromRequest(*ctx.Request(), *ctx.Response())

        })

        return next(ctx)

    }

}

然后將此中間件放在e.Use() 代理中間件之前:


e.POST(

        "/",

        handlers.Noop,

        ACAOHeaderOverwriteMiddleware,

        middleware.ProxyWithConfig(middleware.ProxyConfig{

             Balancer: singleTargetBalancer("[backend service URL]"),

        })

)

Request::Before()Echo鉤子的文檔: https ://echo.labstack.com/guide/response#before-response


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號