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

时间:2017-11-10 06:41:25

标签: javascript http go cookies

我在端口3000

上运行了golang构建的RESTful api

当我在浏览器中导航到http://localhost:3000时,我得到200 (Success)。服务器还成功地向我发送了带有服务器cookie值的JSON。

但是,当我尝试Fetch我的JavaScript SPA中正在端口8080上运行的代码时,我收到401 (Unauthorized)响应。我还收到描述http: named cookie not present的服务器错误。

我已经包含了一个非常简化的版本:

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)
}

我很确定这不是CORS问题。在示例中,我刚刚给出了我得到的错误418 (I'm a teapot)用于演示目的。真正的问题似乎在于服务器错误http: named cookie not present,即使我在浏览器中查看http://localhost:3000处的cookie时也是如此。

我的JavaScript SPA正在端口webpack-dev-server上使用8080运行,所以也许这可能是问题的根源?这就是说我真的希望能够通过webpack在本地测试我的应用程序。

为什么服务器在从JavaScript请求时无法读取cookie?

1 个答案:

答案 0 :(得分:2)

您不能拥有跨域Cookie。

在您的情况下,Cookie会存储在浏览器端,用于网站localhost:8080。 但是,访问localhost:3000时无法使用。

解决方案是使用相同的服务器为您的网站提供服务,或使用GET或POST参数。