我已经为我的 API 文档实现了 go-swagger,该文档在我的本地主机上的不同端口上运行,我的应用程序在端口 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
}
当从 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-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 中间件代码。
这是 swagger 响应的 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
谢谢!