Http 与golang后端的CORS请求不';t工作
我的实现遇到了一些问题。 我有一个用Golang编写的后端,UI(Angular2)在同一台服务器上 我尝试在后端设置CORS处理,但仍然不起作用,我不知道为什么 这是我的密码:Http 与golang后端的CORS请求不';t工作,http,go,cors,Http,Go,Cors,我的实现遇到了一些问题。 我有一个用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
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)
}
身份验证模式工作正常(是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
以下是请求的标题:
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
我使用Negroni作为中间件,代码如下:
func main() {
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"POST", "GET", "OPTIONS", "PUT", "DELETE"},
AllowedHeaders: []string{"Accept", "content-type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
})
router := mux.NewRouter()
router = routers.SetAuthRoute(router)
apiRoutes := routers.InitRoutes()
router.PathPrefix("/api").Handler(negroni.New(
negroni.HandlerFunc(controllers.ValidateTokenMiddleware),
negroni.Wrap(apiRoutes),
))
server := negroni.Classic()
server.Use(c)
server.UseHandler(router)
server.Run("0.0.0.0:" + os.Getenv("PORT"))
}
如前所述,您需要将选项
方法添加到AllowedMethods
数组中
也请考虑添加<代码>接受< /代码>、<代码>接受语言< /代码>和<代码>内容类型< /代码> > <代码>允许的标题< /代码>作为良好的实践。< /P> 如果您不想使用
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)
}
r := mux.NewRouter()
r.Handle("/authentication", handleAuthentication)
http.Handle("/", &CORSRouterDecorator{r})
HTTP服务器
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)
}
r := mux.NewRouter()
r.Handle("/authentication", handleAuthentication)
http.Handle("/", &CORSRouterDecorator{r})
et voilá。与其他两个回答类似,但我的案例我的项目托管在cloud9上,所以我有一些调整要做 这是我添加的代码:
cor := cors.New(cors.Options{
AllowedOrigins: []string{"https://*.c9users.io", "http://myapp.c9users.io:8080", "https://*.c9.io"},
AllowedMethods: []string{"POST", "GET", "OPTIONS", "PUT"},
AllowedHeaders: []string{"Accept", "Accept-Language", "Content-Type"},
AllowCredentials: true,
Debug: true,
});
我不得不添加额外的http源代码,因为Safari使用http而不是https发出初始选项请求
已排序。您是否可以共享chrome devtools的选项请求屏幕截图,该选项请求失败、请求已发送、响应已接收?CORS在执行实际请求之前,使用选项动词检查是否允许跨源。您必须允许选项,并用成功代码(2xx)响应它。