微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从go-swagger UI访问API时Golang中的CORS问题

如何解决从go-swagger UI访问API时Golang中的CORS问题

我为我的api文档实施了wswagger,它在本地主机上的其他端口上运行,而我的应用程序在8888端口上运行。我已经实现了cors https://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
}

在遇到邮递员的请求时,代码似乎运行正常

邮递员响应标题

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-Control-Allow-Origin”标头

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网络呼叫详细信息

HTTP方法=选项

常规

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。