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

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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动