Micah Cowell
Micah Cowell

Reputation: 412

golang api request works in browser but return a 401 (Unauthorized) when requested from JavaScript running locally

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?

Upvotes: 1

Views: 4128

Answers (1)

user2345
user2345

Reputation: 3227

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.

Upvotes: 1

Related Questions