Commit e1f3879a authored by xzj's avatar xzj

pipe支持bodyParser

parent 6c8b87b8
'use strict'
const request = require('request')
const debug = require('debug')('request-proxy')
const qs = require('querystring')
const Agent = require('agentkeepalive');
const HttpsAgent = require('agentkeepalive').HttpsAgent;
......@@ -63,7 +62,7 @@ module.exports = function (options) {
ctx.req.connection.setNoDelay(true)
ctx.curl = function (option, extra) {
if (typeof option === 'string') {
option = {uri: option}
option = {url: option}
}
if (!option.method) {
......@@ -74,11 +73,7 @@ module.exports = function (options) {
extra = Object.assign({}, extraDefault, extra)
if (!isProduction && ctx.request.query['_ip_']) {
if (option.url) {
option.url = rewriteUrl(option.url, ctx.request.query['_ip_'])
} else {
option.uri = rewriteUrl(option.uri, ctx.request.query['_ip_'])
}
option.url = rewriteUrl(option.url, ctx.request.query._ip_)
}
debug(option)
......@@ -110,36 +105,59 @@ module.exports = function (options) {
ctx.pipe = function (option) {
if (typeof option === 'string') {
option = {uri: option}
option = {url: option}
}
option = Object.assign({}, pipeDefault, option)
if (!isProduction && ctx.request.query['_ip_']) {
if (option.url) {
option.url = rewriteUrl(option.url, ctx.request.query['_ip_'])
} else {
option.uri = rewriteUrl(option.uri, ctx.request.query['_ip_'])
}
option.url = rewriteUrl(option.url, ctx.request.query._ip_)
}
if (!option.method) {
option.method = ctx.method
}
debug(option)
if (!option.agent && !/^https/.test(option.url)) {
option.agent = httpAgent
} else if (!option.agent && /^https/.test(option.url)) {
option.agent = httpsAgent
}
return new Promise(function (resolve, reject) {
let r = ctx.req.pipe(request(option, function (err, response) {
let send = function () {
return request(option, function (err, response) {
if (option.time && options.logger) {
options.logger.info(option.url || option.uri, JSON.stringify(response && response.timings || ''))
}
}))
})
}
if (ctx.method === 'POST' && ctx.is('json', 'urlencoded') && ctx.request.body) {
if (ctx.is('urlencoded')) {
option.form = ctx.request.rawBody
} else if (ctx.is('json')) {
option.body = ctx.request.rawBody
}
option.headers = ctx.request.headers
return new Promise(function (resolve, reject) {
let r = send()
r.on('error', function (err) {
console.error(err)
reject(err);
})
.on('response', function () {
ctx.respond = false
r.pipe(ctx.res)
resolve({})
})
})
}
return new Promise(function (resolve, reject) {
let r = ctx.req.pipe(send())
r.on('error', function (err) {
console.error(err)
reject(err);
})
.on('response', function () {
......
{
"name": "request-proxy",
"version": "1.1.2",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment