为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
MM们 2021-07-27 13:56:42
这是我的 AngularJS 代码(如果我删除 header 选项,它可以正常工作)。$http.get(env.apiURL()+'/banks', {    headers: {        'Authorization': 'Bearer '+localStorageService.get('access_token')    }})这是请求:OPTIONS /banks HTTP/1.1Host: localhost:8080Connection: keep-aliveAccess-Control-Request-Method: GETOrigin: http://localhost:8081User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36Access-Control-Request-Headers: accept, authorizationAccept: */*Referer: http://localhost:8081/Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8,vi;q=0.6和回应:HTTP/1.1 404 Not FoundAccess-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, AuthorizationAccess-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETEAccess-Control-Allow-Origin: http://localhost:8081Content-Type: text/plain; charset=utf-8Date: Mon, 17 Mar 2014 11:05:20 GMTContent-Length: 19我添加了Accept和Authorization标头,但请求仍然失败?大写(我的意思是authorizationvs Authorization)会导致失败吗?如果是,我怎样才能让 AngularJS 停止这样做?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")}Go 服务器路由代码:r := mux.NewRouter()r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")http.ListenAndServe(":8080", r)
查看完整描述

1 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

好的,这个问题是因为我无法处理“OPTIONS”请求(要使 CORS 浏览器先发送预检 OPTIONS 请求,然后再发送“真实”请求,如果服务器接受)。

我只需要修改我的 Go 服务器(见评论):


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)

}


查看完整回答
反对 回复 2021-08-02
  • 1 回答
  • 0 关注
  • 206 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信