cookies的使用_什么是Cookies以及如何使用JavaScript与它们一起使用

cookies的使用

🧁 🧁 🧁 not quite… 🍪🍪🍪 Better! The cookie 🍪 is one of the web’s favorite emoji and it’s also one of web’s most important technology.

🧁不太好……🍪🍪🍪好! cookie🍪是网络上最喜欢的表情符号之一,也是网络上最重要的技术之一。

Let’s take a look at what it’s all about, shall we?

让我们看看它的全部内容,对吧?

浏览器Cookie的基础 (The Basics of Browser Cookies)

Browser cookies were introduced to the web in order to keep persistent information about the user. The first use case was to check if a user had already visited Netscape’s website.

浏览器cookie被引入到Web中,以保留有关用户的永久信息。 第一个用例是检查用户是否已经访问了Netscape的网站。

Cookies are strings that have a name field, a value field and additional optional attributes. The values are strings and you can store whatever you think is best for your application. Google Analytics’ _ga is probably one of || the most common cookie out there, it usually looks like this:

Cookies是具有名称字段,值字段和其他可选属性的字符串。 这些值是字符串,您可以存储最适合自己的应用程序的任何内容。 Google Analytics(分析)的_ga可能one of || the one of || the最普通的饼干在那里,它通常是这样的:

  • Name: _ga

    名称 :_ga

  • Value: GA1.3.210706468.1583989741

    :GA1.3.210706468.1583989741

  • Domain: .example.com

    :.example.com

  • Path: /

    路径 :/

  • Expires / Max-Age: 2022-03-12T05:12:53.000Z

    过期/最大年龄 :2022-03-12T05:12:53.000Z

Cookies can store up to 4096 bytes of data (this includes name, value, domain, expiry date and whatever else you can fit in there). You can add a limited number of cookies per domain which changes depending on your browser.

Cookies最多可以存储4096字节的数据(包括名称,值,域,有效期以及您可以在其中容纳的其他内容)。 您可以在每个域中添加数量有限的Cookie,具体取决于您的浏览器。

Cookie是如何创建的 (How Are Cookies Created)

There are two main ways to create cookies:

创建cookie的主要方法有两种:

  • With HTTP you can send Set-Cookie in your HTTP response header. Depending on the technologies you are using for your web server; you can use different tools and libraries to manage cookie headers. These tools should create HTTP responses which will roughly look like this:

    使用HTTP,您可以在HTTP响应标头中发送Set-Cookie 。 取决于您用于Web服务器的技术; 您可以使用其他工具和库来管理Cookie标头。 这些工具应创建大致如下所示的HTTP响应:

HTTP/2.0 200 OK
Content-type: text/html
Set-Cookie: alligator_name=barry
Set-Cookie: tasty_cookie=strawberry
... More http Content

You can add information to your cookies like an expiration date, and security features such as the Secure directive and the HttpOnly flag.

您可以将信息(例如到期日期)和安全功能(例如Secure指令和HttpOnly标志)添加到cookie中。

Set-Cookie: cookie_name=cookie_value; Expires=Wed, 17 Sep 2021 07:00:00 GMT; Secure; HttpOnly

The HttpOnly flag means that the cookies cannot be read or modified by the browser. And Secure means that the cookie can only be transferred over HTTPS. These are really important to protect your application.

HttpOnly标志意味着浏览器无法读取或修改Cookie。 安全意味着Cookie只能通过HTTPS传输。 这些对于保护您的应用程序非常重要。

  • With Javascript it’s a bit trickier to manage Cookies. We have one interface, document.cookie, which stores our cookies and can be reassigned. For example on a site that has Google Analytics installed, and in the developer console, we can do:

    使用Javascript ,管理Cookie会有些棘手。 我们有一个接口document.cookie ,它存储我们的cookie并可以重新分配。 例如,在安装了Google Analytics(分析)的网站上以及在开发者控制台中,我们可以执行以下操作:

console.log(document.cookie)
// logs something like "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741"

// This equal sign does not work as you expect
document.cookie = "alligator=alligator_cookie_content;"
console.log(document.cookie)
// logs "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741; alligator=alligator_cookie_content"
// Notice that the previous piece of code appends the new cookie we created

// A rough implementation of a cookie interface could look like this:
const createCookie = (name, value) => document.cookie = name + '=' + value + ';'
// For a real update we would first check if the cookie exists
const updateCookie = (name, value) => document.cookie = name + '=' + value + ';'
const deleteCookie = (name) => document.cookie = name + '=; Max-Age=-1;';

Cookie的类型 (Types of Cookies)

会话cookie (Session cookies)

Session cookies often refer to a type of cookie that exist until the browser is closed. To setup a session cookie you just need to NOT specify any expiration date.

会话Cookie通常是指在关闭浏览器之前一直存在的一种Cookie。 要设置会话cookie,您只需不指定任何到期日期。

For example, you can store your user’s name in the cookie. Whoever has access to the cookie will have access to the user’s name. Since it is in the cookie we don’t need to add it to our requests.

例如,您可以将用户名存储在cookie中。 有权访问Cookie的人都可以访问用户名。 由于它在Cookie中,因此我们无需将其添加到我们的请求中。

Session cookies is a confusing expression. Session cookies also refer to cookies which you use to manage sessions. Cookies that are deleted when the browser is closed are not the only cookies you can use for session management.

Session cookies是一个令人困惑的表达。 会话cookie也指用于管理会话的cookie。 关闭浏览器时删除的Cookie并非唯一可用于会话管理的Cookie。

Persistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.

当用户关闭持久性Cookie时,浏览器不会将其删除。 这些Cookie的有效期可以在服务器中设置。 您可以将Cookie设置为在一天或十年后过期。

We can differentiate cookies that are on the same domain from cookies which come from third-party providers. The example we gave earlier with Google Analytics is an example of a third-party cookie. Third-party cookies can be used to track user activities. To set a third-party cookie, you have to set ';domain=thirdpartydomain.com'.

我们可以将同一域中的Cookie与第三方提供商的Cookie区分开。 我们之前在Google Analytics(分析)中提供的示例是第三方Cookie的示例。 第三方cookie可以用来跟踪用户活动。 要设置第三方Cookie,您必须设置';domain=thirdpartydomain.com'

Cookies are usually temporary, so you might want to set a precise expiry date. You have two strategies:

Cookies通常是临时的,因此您可能需要设置一个准确的到期日期。 您有两种策略:

  • Use Expires and set a fixed expiration date. The date uses the HTTP date formate: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT. So for example if we want our cookie to expire September 17 2020 we can do:

    使用“ Expires并设置固定的到期日期。 该日期使用HTTP日期格式: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT 。 因此,例如,如果我们希望我们的cookie在2020年9月17日到期,我们可以这样做:

const jacksBirthday = new Date(2020, 8, 17);
document.cookie = 'jacksage=27; expires =' + jacksBirthday.toUTCString() + ';';
  • Using ‘Max-Age’ is not supported by every browser. But it’s the soundest solution. It forces the cookie to expire a certain amount of time (in seconds) after the client receives it:

    并非所有浏览器都支持使用“最大年龄”。 但这是最合理的解决方案。 它强制cookie在客户端收到cookie后一定时间(以秒为单位)过期:
// Expires after one day
const oneDayToSeconds = 24 * 60 * 60;
document.cookie =  'daily_cookie=session_identifierXYZ; max-age = ' + oneDayToSeconds + ';';

🍪 That’s about it! I hope you now have a better idea of how to use cookies on the client side with JavaScript. If you have any question ask us on Twitter. Next time, we will see how to manage sessions with cookies and Express.js.

about就是这样! 希望您现在对如何在JavaScript的客户端使用cookie有更好的了解。 如果您有任何问题,请在Twitter上问我们。 下次,我们将看到如何使用Cookie和Express.js管理会话。

翻译自: https://www.digitalocean.com/community/tutorials/js-what-are-cookies

cookies的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值