1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict';
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | function cookieParser() {
|
16 | return async (req, res) => {
|
17 | const hdr = req.headers['cookie'];
|
18 |
|
19 | if (!hdr)
|
20 | return;
|
21 |
|
22 | req.cookies = parseCookies(hdr);
|
23 | };
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function parseCookies(hdr) {
|
31 | const parts = hdr.split(/; */);
|
32 | const cookies = Object.create(null);
|
33 |
|
34 | for (const part of parts) {
|
35 | const index = part.indexOf('=');
|
36 |
|
37 | let key = part;
|
38 | let value = '';
|
39 |
|
40 | if (index !== -1) {
|
41 | key = part.substring(0, index);
|
42 | value = part.substring(index + 1);
|
43 | if (value[0] === '"')
|
44 | value = value.slice(1, -1);
|
45 | }
|
46 |
|
47 | if (key.length > 0) {
|
48 | try {
|
49 | value = decodeURIComponent(value);
|
50 | } catch (e) {
|
51 | ;
|
52 | }
|
53 | cookies[key] = value;
|
54 | }
|
55 | }
|
56 |
|
57 | return cookies;
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | module.exports = cookieParser;
|