我的实施面临一些问题。我有一个用 Golang 编写的后端和位于同一服务器上的 UI(在 Angular2 中)。
我试图在我的后端设置 CORS 处理,但它仍然不起作用,我不明白为什么。
这是我的代码:
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
var router *mux.Router
func main() {
router = mux.NewRouter()
HandleFuncEx("/authentication", handleAuthentication)
HandleFuncEx("/callA", handleCallA)
HandleFuncEx("/callB", handleCallB)
HandleFuncEx("/callC", handleCallC)
handler := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PATCH"},
AllowedHeaders: []string{"a_custom_header", "content_type"},
}).Handler(router)
http.ListenAndServe(":8000", handler)
}
func HandleFuncEx(pattern string, handler func(http.ResponseWriter, *http.Request)) {
log.Println("handled function", pattern)
router.HandleFunc(pattern, handler)
}
Run Code Online (Sandbox Code Playgroud)
身份验证模式正常工作(是 UI 的第一个调用),所有其他调用都未通过预检请求。为什么会发生?
感谢大家的帮助!
编辑:
这是非工作响应标头的示例:
HTTP/1.1 200 OK
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Date: Fri, 07 Apr 2017 08:33:12 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Run Code Online (Sandbox Code Playgroud)
这些是请求的标头:
OPTIONS /users HTTP/1.1
Host: /* Removed by my company policy */
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: /* Removed by my company policy */
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Access-Control-Request-Headers: access_token
Accept: */*
Referer: /* Removed by my company policy */
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4,la;q=0.2
Run Code Online (Sandbox Code Playgroud)
正如Adrian 所指出的,您需要将OPTIONSMethod添加到AllowedMethods数组中。
也请考虑增加Accept,Accept-Language并Content-Type在AllowedHeaders良好做法。
如果你不想使用这个github.com/rs/cors包,你可以像这样自己编写一个简单的 CORS 装饰器中间件:
CORS 装饰器
import (
"net/http"
"github.com/gorilla/mux"
)
// CORSRouterDecorator applies CORS headers to a mux.Router
type CORSRouterDecorator struct {
R *mux.Router
}
// ServeHTTP wraps the HTTP server enabling CORS headers.
// For more info about CORS, visit https://www.w3.org/TR/cors/
func (c *CORSRouterDecorator) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Type, YourOwnHeader")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
c.R.ServeHTTP(rw, req)
}
Run Code Online (Sandbox Code Playgroud)
HTTP服务器
r := mux.NewRouter()
r.Handle("/authentication", handleAuthentication)
http.Handle("/", &CORSRouterDecorator{r})
Run Code Online (Sandbox Code Playgroud)
等等。