AngularJS $ http获取请求失败并带有自定义标头(在CORS中允许)

时间:2014-03-17 11:11:56

标签: javascript angularjs cross-browser go cors

这是我的JS代码,(如果我删除标题选项,它可以正常工作)。

$http.get(env.apiURL()+'/banks', {
    headers: {
        'Authorization': 'Bearer '+localStorageService.get('access_token')
    }
})

以下是请求:

OPTIONS /banks HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:8081
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://localhost:8081/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,vi;q=0.6

并回复:

HTTP/1.1 404 Not Found
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: http://localhost:8081
Content-Type: text/plain; charset=utf-8
Date: Mon, 17 Mar 2014 11:05:20 GMT
Content-Length: 19

我添加了接受授权标题,但为什么请求仍然失败?
这种情况(我的意思是授权 vs 授权)会导致失败吗?如果是,我怎么能让AngularJS停止这样做呢? 谢谢:)

P / s:这是我在Go中写的服务器代码:

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 个答案:

答案 0 :(得分:8)

好的,问题是因为我要处理“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)
}