如何阅读Cookie? [英] How to read cookies?

查看:113
本文介绍了如何阅读Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从javascript设置了cookie,例如:

I set a cookie from javascript such as:

setCookie("appointment", JSON.stringify({
                appointmentDate: selectedDay.date,
                appointmentStartMn: appointment.mnRange[0],
                appointmentId: appointment.id || 0,
                appointmentUserId: appointment.user.id || 0
          })
);

设置cookie后,我要将用户重定向到预订页面:

After cookie is set I want to redirect the user to a booking page:

window.location.href = "https://localhost:8080/booking/"

setCookie函数:

The setCookie function:

function setCookie(cookieName, cookieValue) {
    document.cookie = `${cookieName}=${cookieValue};secure;`;
}

我想从我的go后端检索该cookie,但我不知道如何去做这个。我已经读过有关此问题的信息,因为我以前从未使用过Cookie,但是答案似乎表明,除了设置document.cookie之外,我不必做其他事情。

I'd like to retrieve that cookie from my go backend but I can't figure out how to do this. I've read about this question since I've never used cookies before but the answers seems to tell that I don't have to do much aside from setting document.cookie.

在我的浏览器存储中,我可以看到cookie确实已按预期设置。

In my browser storage I can see the cookie is indeed set as expected.

在我的后端中,我要打印cookie:

In my Go back end I want to print the cookie:

r.HandleFunc("/booking/", handler.serveTemplate)

func (handler *templateHandler) serveTemplate(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("appointment")
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(c.Value)
    }
}

//output http: named cookie not present

我想念的具体是什么?我认为我混淆了本地/ http cookie,但是如何实现读取客户端设置cookie?

What is the specific I am missing ? I think I'm confusing local/http cookie but how to achieve the reading of client set cookies?

UPDATE(请参阅答案以了解更多信息)

它与golang无关。我的:

It has nothing to do with golang. My:

appointmentDate: selectedDay.date

格式化为 2019-01-01 -的格式不是可以发送到后端的有效字符。它可以在我的浏览器中使用,但是需要经过URI编码才能传递。

What formatted as 2019-01-01 and - is not a valid character that can be send to the backend. It worked into my browser, but it needs to be URI encoded to be passed.

所以这可以解决问题:

`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`

然后进入(在这里找不到错误以节省空间):

And in go (didn't catch err here to save space):

cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)


推荐答案

例如,更好的方法是将json编码为base64。我做了一个有效的例子...

A better way would be to encode your json into base64 for example. I made a working example...

main.go

package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
)

// Contains everything about an appointment
type Appointment struct {
    Date    string `json:"appointmentDate"`    // Contains date as string
    StartMn string `json:"appointmentStartMn"` // Our startMn ?
    ID      int    `json:"appointmentId"`      // AppointmentId
    UserID  int    `json:"appointmentUserId"`  // UserId
}

func main() {
    handler := http.NewServeMux()

    // Main request
    handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read file
        b, _ := ioutil.ReadFile("index.html")
        io.WriteString(w, string(b))
    })

    // booking request
    handler.HandleFunc("/booking/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /booking/\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read cookie
        cookie, err := r.Cookie("appointment")
        if err != nil {
            fmt.Printf("Cant find cookie :/\r\n")
            return
        }

        fmt.Printf("%s=%s\r\n", cookie.Name, cookie.Value)

        // Cookie data
        data, err := base64.StdEncoding.DecodeString(cookie.Value)
        if err != nil {
            fmt.Printf("Error:", err)
        }

        var appointment Appointment
        er := json.Unmarshal(data, &appointment)
        if err != nil {
            fmt.Printf("Error: ", er)
        }

        fmt.Printf("%s, %s, %d, %d\r\n", appointment.Date, appointment.StartMn, appointment.ID, appointment.UserID)

        // Read file
        b, _ := ioutil.ReadFile("booking.html")
        io.WriteString(w, string(b))
    })

    // Serve :)
    http.ListenAndServe(":8080", handler)
}

index.html

index.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Setting cookie via Javascript

    <script type="text/javascript">
    window.onload = () => {
        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + btoa((value || ""))  + expires + "; path=/";
        }

        setCookie("appointment", JSON.stringify({
                    appointmentDate: "20-01-2019 13:06",
                    appointmentStartMn: "1-2",
                    appointmentId: 2,
                    appointmentUserId: 3
            })
        );

        document.location = "/booking/";
    }
    </script>
</body>

booking.html

booking.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Your booking is okay :)
</body>

这篇关于如何阅读Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆