duanjuda5789 2017-09-29 19:15
浏览 185
已采纳

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

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 2017-09-30 14:01
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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