且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自定义标头获取请求失败

更新时间:2022-03-03 22:46:48

好,这是因为我无法处理"OPTIONS"请求(要使CORS浏览器先发送预检OPTIONS请求,然后再发送"real"请求(如果服务器接受).
我只需要修改我的Go服务器(请参阅评论):

OK, the issue because I fotgot to handle the "OPTIONS" request (to make a CORS browser will send a preflight OPTIONS request first and then the 'real' request if accepted by the server).
I only need to modify my Go server (see the comment):

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
    http.ListenAndServe(":8080", &MyServer{r})
}

type MyServer struct {
    r *mux.Router
}

func (s *IMoneyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
        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, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}