duanjuda5789
duanjuda5789
2017-09-29 19:15

无法在React应用(CORS)中从服务器端(golang)获取Cookie

  • cookies
  • reactjs
已采纳

I have a quite simple server application written in go:

package main

import (
    "fmt"
    "math/rand"
    "time"
    "net/http"
    "encoding/base64"
    "encoding/json"
    "github.com/rs/cors"
)

type Message struct {
    Text string `json:"text"`
}

var cookieQuotes = []string{
    ...
}

const COOKIE_NAME = "your_cookie"

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/set_cookie", setCookie)
    mux.HandleFunc("/get_cookie", getCookie)
    mux.Handle("/favicon.ico", http.NotFoundHandler())
    handler := cors.Default().Handler(mux)
    http.ListenAndServe(":8080", handler)
}

...

Well, I have skipped the most of code here, but let me explain what it does.

When we go to /set_cookie path, we are getting a cookie to our browser. Cookie has a Value, which is encrypted text of quote about a cookie. So, here is the function:

func setCookie(w http.ResponseWriter, r *http.Request) {
    quote := getRandomCookieQuote()
    encQuote := base64.StdEncoding.EncodeToString([]byte(quote))
    http.SetCookie(w, &http.Cookie{
        Name: COOKIE_NAME,
        Value: encQuote,
    })
}

This app is deployed in VirtualBox in a docker container.

So, when I'm accessing the

http://IP_ADDRESS:PORT/set_cookie

the cookie is set to the browser. And when I access

http://IP_ADDRESS:PORT/get_cookie

I get decrypted text from a cookie (but this doesn't matter in case of this question)

The client side is written in React. Well, I think it is not necessary to post all the code of the application, but the main part is here:

export const setCookie = () => async dispatch => {
  const res = await axios.get(URL+SET_COOKIE_PATH);
  console.log('set_cookie', res);
};

It is the the same thing as if we just called

http://IP_ADDRESS:PORT/set_cookie

But I can't get the cookie to the browser. Never. I get the response with status code 200 and everything seems to be okay, but I don't get a cookie.

I have to mention, that this is a cross site thing.

So, the question is: How could I pass cookie from server to client?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douhuigang9550 douhuigang9550 4年前

    The solution is to write proxy variable in package.json to get of CORS

    For example, if client is on localhost:3000 and server is on localhost:8080, we should add:

    "proxy": "http://localhost:8080/"

    And access any path of server API with domain of client side, like:

    http://localhost:3000/set_coookie

    点赞 评论 复制链接分享