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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料