Projekt

Obecné

Profil

Stáhnout (8.6 KB) Statistiky
| Větev: | Revize:
1
# cookie
2

    
3
[![NPM Version][npm-version-image]][npm-url]
4
[![NPM Downloads][npm-downloads-image]][npm-url]
5
[![Node.js Version][node-version-image]][node-version-url]
6
[![Build Status][travis-image]][travis-url]
7
[![Test Coverage][coveralls-image]][coveralls-url]
8

    
9
Basic HTTP cookie parser and serializer for HTTP servers.
10

    
11
## Installation
12

    
13
```sh
14
$ npm install cookie
15
```
16

    
17
## API
18

    
19
```js
20
var cookie = require('cookie');
21
```
22

    
23
### cookie.parse(str, options)
24

    
25
Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
26
The `str` argument is the string representing a `Cookie` header value and `options` is an
27
optional object containing additional parsing options.
28

    
29
```js
30
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
31
// { foo: 'bar', equation: 'E=mc^2' }
32
```
33

    
34
#### Options
35

    
36
`cookie.parse` accepts these properties in the options object.
37

    
38
##### decode
39

    
40
Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
41
has a limited character set (and must be a simple string), this function can be used to decode
42
a previously-encoded cookie value into a JavaScript string or other object.
43

    
44
The default function is the global `decodeURIComponent`, which will decode any URL-encoded
45
sequences into their byte representations.
46

    
47
**note** if an error is thrown from this function, the original, non-decoded cookie value will
48
be returned as the cookie's value.
49

    
50
### cookie.serialize(name, value, options)
51

    
52
Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
53
name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
54
argument is an optional object containing additional serialization options.
55

    
56
```js
57
var setCookie = cookie.serialize('foo', 'bar');
58
// foo=bar
59
```
60

    
61
#### Options
62

    
63
`cookie.serialize` accepts these properties in the options object.
64

    
65
##### domain
66

    
67
Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no
68
domain is set, and most clients will consider the cookie to apply to only the current domain.
69

    
70
##### encode
71

    
72
Specifies a function that will be used to encode a cookie's value. Since value of a cookie
73
has a limited character set (and must be a simple string), this function can be used to encode
74
a value into a string suited for a cookie's value.
75

    
76
The default function is the global `encodeURIComponent`, which will encode a JavaScript string
77
into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
78

    
79
##### expires
80

    
81
Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1].
82
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
83
will delete it on a condition like exiting a web browser application.
84

    
85
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
86
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
87
so if both are set, they should point to the same date and time.
88

    
89
##### httpOnly
90

    
91
Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy,
92
the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
93

    
94
**note** be careful when setting this to `true`, as compliant clients will not allow client-side
95
JavaScript to see the cookie in `document.cookie`.
96

    
97
##### maxAge
98

    
99
Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2].
100
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
101

    
102
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
103
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
104
so if both are set, they should point to the same date and time.
105

    
106
##### path
107

    
108
Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
109
is considered the ["default path"][rfc-6265-5.1.4].
110

    
111
##### sameSite
112

    
113
Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7].
114

    
115
  - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
116
  - `false` will not set the `SameSite` attribute.
117
  - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
118
  - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
119
  - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
120

    
121
More information about the different enforcement levels can be found in
122
[the specification][rfc-6265bis-03-4.1.2.7].
123

    
124
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
125
This also means many clients may ignore this attribute until they understand it.
126

    
127
##### secure
128

    
129
Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
130
the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
131

    
132
**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
133
the server in the future if the browser does not have an HTTPS connection.
134

    
135
## Example
136

    
137
The following example uses this module in conjunction with the Node.js core HTTP server
138
to prompt a user for their name and display it back on future visits.
139

    
140
```js
141
var cookie = require('cookie');
142
var escapeHtml = require('escape-html');
143
var http = require('http');
144
var url = require('url');
145

    
146
function onRequest(req, res) {
147
  // Parse the query string
148
  var query = url.parse(req.url, true, true).query;
149

    
150
  if (query && query.name) {
151
    // Set a new cookie with the name
152
    res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
153
      httpOnly: true,
154
      maxAge: 60 * 60 * 24 * 7 // 1 week
155
    }));
156

    
157
    // Redirect back after setting cookie
158
    res.statusCode = 302;
159
    res.setHeader('Location', req.headers.referer || '/');
160
    res.end();
161
    return;
162
  }
163

    
164
  // Parse the cookies on the request
165
  var cookies = cookie.parse(req.headers.cookie || '');
166

    
167
  // Get the visitor name set in the cookie
168
  var name = cookies.name;
169

    
170
  res.setHeader('Content-Type', 'text/html; charset=UTF-8');
171

    
172
  if (name) {
173
    res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
174
  } else {
175
    res.write('<p>Hello, new visitor!</p>');
176
  }
177

    
178
  res.write('<form method="GET">');
179
  res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
180
  res.end('</form>');
181
}
182

    
183
http.createServer(onRequest).listen(3000);
184
```
185

    
186
## Testing
187

    
188
```sh
189
$ npm test
190
```
191

    
192
## Benchmark
193

    
194
```
195
$ npm run bench
196

    
197
> cookie@0.3.1 bench cookie
198
> node benchmark/index.js
199

    
200
  http_parser@2.8.0
201
  node@6.14.2
202
  v8@5.1.281.111
203
  uv@1.16.1
204
  zlib@1.2.11
205
  ares@1.10.1-DEV
206
  icu@58.2
207
  modules@48
208
  napi@3
209
  openssl@1.0.2o
210

    
211
> node benchmark/parse.js
212

    
213
  cookie.parse
214

    
215
  6 tests completed.
216

    
217
  simple      x 1,200,691 ops/sec ±1.12% (189 runs sampled)
218
  decode      x 1,012,994 ops/sec ±0.97% (186 runs sampled)
219
  unquote     x 1,074,174 ops/sec ±2.43% (186 runs sampled)
220
  duplicates  x   438,424 ops/sec ±2.17% (184 runs sampled)
221
  10 cookies  x   147,154 ops/sec ±1.01% (186 runs sampled)
222
  100 cookies x    14,274 ops/sec ±1.07% (187 runs sampled)
223
```
224

    
225
## References
226

    
227
- [RFC 6265: HTTP State Management Mechanism][rfc-6265]
228
- [Same-site Cookies][rfc-6265bis-03-4.1.2.7]
229

    
230
[rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
231
[rfc-6265]: https://tools.ietf.org/html/rfc6265
232
[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
233
[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
234
[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
235
[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
236
[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
237
[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
238
[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
239
[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
240

    
241
## License
242

    
243
[MIT](LICENSE)
244

    
245
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
246
[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
247
[node-version-image]: https://badgen.net/npm/node/cookie
248
[node-version-url]: https://nodejs.org/en/download
249
[npm-downloads-image]: https://badgen.net/npm/dm/cookie
250
[npm-url]: https://npmjs.org/package/cookie
251
[npm-version-image]: https://badgen.net/npm/v/cookie
252
[travis-image]: https://badgen.net/travis/jshttp/cookie/master
253
[travis-url]: https://travis-ci.org/jshttp/cookie
(3-3/5)