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?