dqitk20644 2017-11-10 06:41
浏览 250
已采纳

golang api请求可在浏览器中使用,但从本地运行的JavaScript请求时返回401(未授权)

I have a RESTful api built with golang running on port 3000

When I navigate in my browser to http://localhost:3000 I get a 200 (Success). The server also successfully sends me the JSON with a value from the server cookies.

However, when I try to Fetch the code from within my JavaScript SPA which is being run on port 8080, I get a 401 (Unauthorized) response. I also get a server error describing http: named cookie not present.

I've included a very stripped down version:

myapp.js

fetch("http://localhost:3000/authenticate")
    .then((r) => {
        return r;
    })
    .then((r) => {
        console.log(r)
    })

server.go

package main

// func respond(w http.ResponseWriter, value *string, status int)
// writes header and encoded json

func main() {
    http.HandleFunc("/authenticate", func(w http.ResponseWriter, r *http.Request){
        cookie, err := r.Cookie("cookie_name")
        if err != nil {
            // here's where I get the server error
            fmt.Println(err)
            respond(w, nil, http.StatusTeapot)
            return
        }
        respond(w, cookie.Value, http.StatusOK)
    })
    c := cors.New(cors.Options{
        AllowedOrigins:   []string{"http://localhost:8080"},
        AllowCredentials: true,
    })
    handler := c.Handler(mux)
    http.ListenAndServe(":3000", handler)
}

I'm pretty sure it's not a CORS problem. In the example I just gave the error I get is 418 (I'm a teapot) for demonstration purposes. The real problem seems to lie in the server error saying http: named cookie not present, even though when I look at the cookies at http://localhost:3000 in my browser it's there.

My JavaScript SPA is being run with webpack-dev-server on port 8080, so maybe that could be a source of the problem? That said I would really like to be able to test my app locally with webpack.

Why can't the server read the cookie when being requested from JavaScript?

  • 写回答

1条回答 默认 最新

  • duanfen9090 2017-11-10 06:48
    关注

    You cannot have cross-domain cookies.

    In your case, a cookie is stored on the browser side for site localhost:8080. It is however not available when accessing localhost:3000.

    A solution would be to serve your website with the same server, or use GET or POST parameters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?