第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

從 go-swagger UI 訪問 API 時 Golang 中的 CORS 問題

從 go-swagger UI 訪問 API 時 Golang 中的 CORS 問題

Go
犯罪嫌疑人X 2022-07-11 10:47:38
我已經(jīng)為我的 API 文檔實現(xiàn)了 go-swagger,該文檔在我的本地主機上的不同端口上運行,我的應(yīng)用程序在端口 8888 上運行。我已經(jīng)實現(xiàn)了 cors https://github.com/rs/cors我實現(xiàn) cors 的代碼是var Router = func() *mux.Router{    router := mux.NewRouter()    var c = cors.New(cors.Options{        AllowedOrigins: []string{"*"},        AllowCredentials: true,        AllowedMethods :[]string{"POST", "PUT","GET","DELETE","OPTIONS"},        AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},        MaxAge: 300,        // Enable Debugging for testing, consider disabling in production        Debug: true,    })    RegisterHandler := http.HandlerFunc(controllers.Register)    router.Handle("/api/register",c.Handler(middleware.RequestValidator(RegisterHandler,reflect.TypeOf(dto.UserRequest{})))).Methods("POST")    fmt.Println("var1 = ", reflect.TypeOf(router))     return router}當(dāng)從 Postman 發(fā)出請求時,似乎代碼運行良好郵遞員響應(yīng)標(biāo)頭access-control-allow-credentials →trueaccess-control-allow-origin →*content-length →123content-type →application/jsondate →Wed, 14 Oct 2020 04:02:37 GMTvary →Origin 由于我在實現(xiàn)我的控制臺上打印的 cors 中間件日志時啟用了調(diào)試,如下所示控制臺日志[cors] 2020/10/14 09:32:37 Handler: Actual request[cors] 2020/10/14 09:32:37   Actual response added headers: map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[*] Vary:[Origin]]問題當(dāng)我在瀏覽器中從 Swagger-UI 訪問相同的 API 時,我遇到了未設(shè)置“Access-Control-Allow-Origin”標(biāo)頭的問題Access to fetch at 'http://localhost:8888/api/register' from origin 'http://localhost:45601' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.并且控制臺上沒有打印日志。從 Swagger UI 訪問 API 時,似乎無法訪問 cors 中間件代碼。這是 swagger 響應(yīng)的 Bowser 網(wǎng)絡(luò)調(diào)用詳細(xì)信息
查看完整描述

2 回答

?
滄海一幻覺

TA貢獻(xiàn)1824條經(jīng)驗 獲得超5個贊

您需要OPTIONS在路由器上允許方法。

https://github.com/abhimanyu1990/go-connect/blob/main/app/conf/router.configuration.go#L30

router.Handle("/api/register", c.Handler(middleware.RequestValidator(RegisterHandler, reflect.TypeOf(dto.UserRequest{})))).Methods("POST", "OPTIONS")



查看完整回答
反對 回復(fù) 2022-07-11
?
萬千封印

TA貢獻(xiàn)1891條經(jīng)驗 獲得超3個贊

當(dāng)我嘗試啟用 CORS 并在 Go 中寫入標(biāo)頭時,這很煩人。最后,我創(chuàng)建了一個包裝 ResponseWriter 的結(jié)構(gòu)來檢測標(biāo)頭是否已經(jīng)寫入并且它工作正常。


package router


import (

    "log"

    "net/http"

)


const (

    noWritten     = -1

    defaultStatus = http.StatusOK

)


type ResponseWriter struct {

    writer http.ResponseWriter

    size   int

    status int

}


func (w *ResponseWriter) Writer() http.ResponseWriter {

    return w.writer

}


func (w *ResponseWriter) WriteHeader(code int) {

    if code > 0 && w.status != code {

        if w.Written() {

            log.Printf("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)

        }

        w.status = code

    }

}


func (w *ResponseWriter) WriteHeaderNow() {

    if !w.Written() {

        w.size = 0

        w.writer.WriteHeader(w.status)

    }

}


func (w *ResponseWriter) Write(data []byte) (n int, err error) {

    w.WriteHeaderNow()

    n, err = w.writer.Write(data)

    w.size += n

    return

}


func (w *ResponseWriter) Status() int {

    return w.status

}


func (w *ResponseWriter) Size() int {

    return w.size

}


func (w *ResponseWriter) Written() bool {

    return w.size != noWritten

}

在回應(yīng)中:


func respondJSON(w *router.ResponseWriter, status int, payload interface{}) {

    res, err := json.Marshal(payload)

    if err != nil {

        respondError(w, internalErrorStatus.number, internalErrorStatus.description)

        return

    }


    go w.WriteHeader(status)

    header := w.Writer().Header()

    header.Add("Access-Control-Allow-Origin", "*")

    header.Add("Content-Type", "application/json")

    header.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")

    header.Add("Access-Control-Allow-Headers", "*")


    w.Write([]byte(res))

}


查看完整回答
反對 回復(fù) 2022-07-11
  • 2 回答
  • 0 關(guān)注
  • 318 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號