dty5753 2019-04-08 15:06
浏览 422
已采纳

当我使用POSTMAN对golang api进行POST请求时,我成功地将jwt令牌作为cookie接收到,但是当我从浏览器中获取时,没有cookie

I have made an API in golang. Backend and frontend are running on separate servers. When I test the API with POSTMAN everything works fine and I receive the cookie containing the jwt token but when I do the request from the frontend then no cookie is received.

Here is the middleware for handling CORS:

func corsHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // origin := r.Header.Get("Origin")
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5000")
        if r.Method == "OPTIONS" {
            w.Header().Set("Access-Control-Allow-Credentials", "true")
            w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")

            w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, Authorization, access-control-allow-origin")
            return
        }
        h.ServeHTTP(w, r)
    })
}

Following is the cookie generator:

    jwtCookie := &http.Cookie{
        Name:   "jwtToken",
        Secure: false,
        HttpOnly: true,
        Value:    tokenString,
        Expires:  expiryTime,
    }

    http.SetCookie(w, jwtCookie)
    w.Header().Add("Access-Control-Allow-Credentials", "true")
    w.WriteHeader(http.StatusOK)

Following is the ajax request:

       $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/api/signin',
            data: JSON.stringify({
                "username": $('#username').val(),
                "password": $('#password').val()
            }),
            xhrFields: { withCredentials: true },
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
                console.log(data);
            },
            error: function(message) {
                console.log(message.responseJSON);
            }
        });

In firefox the response header looks like this: As you can see in image 1, the cookie is received in header but it is not visible in storage

In chrome the response header looks like: there is no cookie visible in chrome

I am stuck on this for quite a long time. Any help would be valuable :)

  • 写回答

2条回答 默认 最新

  • dongwei4652 2019-04-13 14:34
    关注

    I had to add w.Header().Add("Access-Control-Allow-Credentials", "true") for all the requests and not just OPTIONS preflight request and also it turned out that chrome was not showing the cookie in storage but it was present and working as expected, later I checked in firefox and the cookie was visible in storage.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真