从go-swager UI访问API时,Golang出现CORS问题



我为我的API文档实现了go-swager,该文档运行在本地主机上的另一个端口上,我的应用程序运行在端口8888上。我已经实施了corshttps://github.com/rs/cors

我实现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
}

当点击Postman的请求时,代码似乎运行良好

邮差响应头

access-control-allow-credentials →true
access-control-allow-origin →*
content-length →123
content-type →application/json
date →Wed, 14 Oct 2020 04:02:37 GMT
vary →Origin 

由于我在实现cors中间件时启用了调试,所以在控制台上打印的日志如下

控制台日志

[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]]

问题

当我在浏览器中从Swagger-UI访问相同的API时;访问控制允许起源";标头未设置

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中间件代码

以下是bowser网络呼叫对swagger 的响应细节

HTTP METHOD=OPTIONS

通用

Request URL: http://localhost:8888/api/register
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: [::1]:8888
Referrer Policy: strict-origin-when-cross-origin

响应标头

Content-Length: 0
Date: Wed, 14 Oct 2020 04:25:23 GMT

请求头

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en-IN;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8888
Origin: http://localhost:45601
Pragma: no-cache
Referer: http://localhost:45601/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36

提取

通用

Request URL: http://localhost:8888/api/register
Referrer Policy: strict-origin-when-cross-origin

请求头

Provisional headers are shown
accept: application/json
Content-Type: application/json
Referer: http://localhost:45601/
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36

谢谢!

您需要在路由器上允许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")

当我试图启用CORS并在Go中写入标头时,这很烦人。最后,我创建了一个结构包装ResponseWriter来检测头是否已经写入,并且它工作正常。

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
}

在回应中:

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

相关内容

  • 没有找到相关文章

最新更新