diff --git a/Readme.md b/Readme.md index 685cea3..f3c9849 100644 --- a/Readme.md +++ b/Readme.md @@ -124,3 +124,10 @@ request.header() // {'user-agent': '...'[, ...]} > 获取客户端IP地址. > > It would return '127.0.0.1' maybe if in local area network. + + +### cookie(key) + +> 获取客户端带上的cookie. +> 不传key时返回所有的 + diff --git a/index.js b/index.js index 9821981..8ca30e2 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,7 @@ import 'es.shim' import Parser from './lib/index.js' +import { parseCookie } from './lib/cookie.js' import fs from 'iofs' import URL from 'url' import QS from 'querystring' @@ -29,6 +30,7 @@ export default class Request { hideProperty(this, 'origin', { req, res }) hideProperty(this, '__GET__', null) hideProperty(this, '__POST__', null) + hideProperty(this, '__COOKIE__', parseCookie(this.header('cookie') || '')) this.__fixUrl() @@ -260,6 +262,14 @@ export default class Request { return !!key ? this.origin.req.headers[key] : this.origin.req.headers } + // 读取cookie + cookie(key) { + if (key) { + return this.__COOKIE__[key] + } + return this.__COOKIE__ + } + //获取客户端IP ip() { return ( diff --git a/lib/cookie.js b/lib/cookie.js new file mode 100644 index 0000000..4c10d6d --- /dev/null +++ b/lib/cookie.js @@ -0,0 +1,36 @@ +/** + * @author yutent + * @date 2020/09/20 15:08:50 + */ + +// var KEY_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ +var SPLIT_REGEXP = /; */ +// var encode = encodeURIComponent +var decode = decodeURIComponent + +/** + * [parse 格式化字符串] + */ +export function parseCookie(str) { + var obj = {} + var pairs + + if (typeof str !== 'string') { + return {} + } + + pairs = str.split(SPLIT_REGEXP) + + for (let item of pairs) { + item = item.split('=') + if (item.length < 2) { + continue + } + + var key = item[0].trim() + var val = item[1].trim() + + obj[key] = decode(val) + } + return obj +} diff --git a/package.json b/package.json index 9ce36b1..b4a7e1b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@gm5/request", - "version": "1.1.0", + "version": "1.2.0", "description": "对Http的request进一步封装, 提供常用的API", "main": "index.js", "author": "yutent",