How do both the front end and back end read and write cookies?

Mondo Technology Updated on 2024-03-02

You should have seen some**, on the first visit, it will pop up some tips or operation instructions, similar to the following picture:

When I turn off this prompt, it doesn't pop up again. When I close the browser and open it again, it doesn't pop up again. However, if you look at the upper right corner of the screenshot, you can see that I am not logged in, so how did you "remember" that I turned off this prompt? This is actually recorded through cookies. When I click the x to dismiss the prompt, the j**ascript will write a flag to the cookie. Every time we open this new page, it will determine whether there is this mark in the cookie. If there is no such mark, a prompt will pop up. If there is such a mark, it will not pop up.

A cookie is essentially a long string of characters separated by semicolons, each consisting of a key and a value, called a cookie.

When we want to add a cookie to a cookie, there are two common ways to add a cookie: using j**ascript or through the backend settings.

To read all current cookies, you can use **:

document.cookie
The running effect is shown in the following figure:

Note that if you want to determine if a key value is in a cookie, then you need to do a string match. This is not the case with objects, which cannot directly find value based on the key or determine whether the key is in it.

To write a cookie, we can use **:

document.cookie = 'key=value'
For example:

Here we usedocument.cookie = new value, which may look like it's covering the entire cookie, but it's not. If you add the same key as the existing one, it will overwrite the value of the original cookie and will not affect the other cookies. If your new key is not in the original cookie, it will be added to the end.

Another way to set cookies on the backend is to use FastAPI as an example

The first is to write cookies to the browser, using the following **:

from fastapi import fastapi, responseapp = fastapi()

app.get('/')

def index(response: response, name: str = ''):

if not name:

name = 'kingname'

response.set_cookie('name', name)

return Hello, the value of the info field in your cookies is:'

return Hello, the value of the info field in your cookies is: , is it a new user:'

return {'success': true, 'msg': msg

The running effect is shown in the following figure:

Regardless of whether you use the front-end or back-end method, you can store some information in the cookie to implement certain switches or record some information.

Related Pages