增加cookie读取

v1
宇天 2020-09-21 17:57:42 +08:00
parent c66603b826
commit de0d16d15c
4 changed files with 54 additions and 1 deletions

View File

@ -124,3 +124,10 @@ request.header() // {'user-agent': '...'[, ...]}
> 获取客户端IP地址. > 获取客户端IP地址.
> >
> It would return '127.0.0.1' maybe if in local area network. > It would return '127.0.0.1' maybe if in local area network.
### cookie(key)
> 获取客户端带上的cookie.
> 不传key时返回所有的

View File

@ -6,6 +6,7 @@
import 'es.shim' import 'es.shim'
import Parser from './lib/index.js' import Parser from './lib/index.js'
import { parseCookie } from './lib/cookie.js'
import fs from 'iofs' import fs from 'iofs'
import URL from 'url' import URL from 'url'
import QS from 'querystring' import QS from 'querystring'
@ -29,6 +30,7 @@ export default class Request {
hideProperty(this, 'origin', { req, res }) hideProperty(this, 'origin', { req, res })
hideProperty(this, '__GET__', null) hideProperty(this, '__GET__', null)
hideProperty(this, '__POST__', null) hideProperty(this, '__POST__', null)
hideProperty(this, '__COOKIE__', parseCookie(this.header('cookie') || ''))
this.__fixUrl() this.__fixUrl()
@ -260,6 +262,14 @@ export default class Request {
return !!key ? this.origin.req.headers[key] : this.origin.req.headers 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
ip() { ip() {
return ( return (

36
lib/cookie.js Normal file
View File

@ -0,0 +1,36 @@
/**
* @author yutent<yutent.io@gmail.com>
* @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
}

View File

@ -1,6 +1,6 @@
{ {
"name": "@gm5/request", "name": "@gm5/request",
"version": "1.1.0", "version": "1.2.0",
"description": "对Http的request进一步封装, 提供常用的API", "description": "对Http的request进一步封装, 提供常用的API",
"main": "index.js", "main": "index.js",
"author": "yutent", "author": "yutent",