1 Star 0 Fork 2

liuzy88 / jiqid

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
proxy.js 2.51 KB
一键复制 编辑 原始数据 按行查看 历史
liuzy 提交于 2020-11-07 01:22 . init
const URL = require('url')
const http = require('http')
const zlib = require('zlib')
const querystring = require('querystring')
const proxy = {}
proxy.GET = function(url, headers) {
return request(false, url, headers)
}
proxy.POST = function(url, headers, form) {
return request(true, url, headers, form)
}
function request(isPOST, url, headers, form) {
return new Promise((revlose, reject)=>{
headers = headers || {}
form = form || {}
let postData = querystring.stringify(form)
let options = URL.parse(url)
options.method = isPOST ? 'POST' : 'GET'
options.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,zh-TW;q=0.6',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': options.host,
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
}
if (isPOST) {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
options.headers['Content-Length'] = postData.length
}
for (let k in headers) {
options.headers[k] = headers[k]
}
let req = http.request(options, (res) => {
res.setTimeout(3000)
let data = []
res.on('data', (chunk) => {
data.push(chunk)
})
res.on('end', () => {
let body = data.join('')
if (res.headers['content-encoding'] == 'gzip') { // Gzip支持
zlib.gunzip(Buffer.concat(data), function(err, decoded) {
if (err) {
revlose({ code: res.statusCode, headers: res.headers, body: body })
} else {
revlose({ code: res.statusCode, headers: res.headers, body: decoded.toString() })
}
})
} else {
revlose({ code: res.statusCode, headers: res.headers, body: body })
}
})
})
req.setTimeout(3000)
req.on('error', (err) => {
reject(err)
})
if (isPOST) {
req.write(postData)
}
req.end()
})
}
module.exports = proxy
1
https://gitee.com/liuzy1988/jiqid.git
git@gitee.com:liuzy1988/jiqid.git
liuzy1988
jiqid
jiqid
master

搜索帮助