diff --git a/changelog.md b/changelog.md index 42da62c..0a7c16d 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,7 @@ +# v0.4.0 +## Add +1. Add the property of `_res_data` to `http.ServerResponse` when come across proxy request error, such as the request is timeout or the backend is broken. + # v0.3.0 ## Add 1. Add the parameter of `agent` to enable `keep-alive` in http request. diff --git a/lib/proxy.js b/lib/proxy.js index 5dc44e8..6fc6b38 100644 --- a/lib/proxy.js +++ b/lib/proxy.js @@ -69,17 +69,25 @@ const checkUrl = function(req, urlsToProxy, urlKeys, callback) { * @property {http.Agent=} agent The instance of the class of http.Agent. */ +const _sendStatus = function(res, statusCode, message) { + res._res_code = message; + res.status(statusCode).end(message); +}; const DEFAULT_INIT_CONFIG = { + // eslint-disable-next-line no-unused-vars onError: function(err, agentUrl) { }, dataPrepare: function(data) { return data; }, + // eslint-disable-next-line no-unused-vars headerPrepare: function(req) { return {}; }, + beforeRequest: function() {}, + afterRequest: function() {}, timeout: 10000, jsonDisabled: false }; @@ -119,11 +127,11 @@ const _doProxy = function(options, agentUrl, req, res) { proxyReq.setNoDelay(true); proxyReq.setTimeout(timeout, function() { proxyReq.abort(); - res.status(504).end('proxy ' + agentUrl +' timeout'); + _sendStatus(res, 504, 'proxy ' + agentUrl +' timeout'); }); proxyReq.on('error', function(err) {//TODO check slogger.error('proxy ' + agentUrl +' error',err); - res.status(500).end('proxy ' + agentUrl +' error'); + _sendStatus(res, 500, 'proxy ' + agentUrl +' error'); }); req.pipe(proxyReq); @@ -178,7 +186,7 @@ const _doProxy = function(options, agentUrl, req, res) { apiGateWayReq.on('error', function(err) { slogger.error('request proxy http interface failed', err, reqOptions); if (err.code === 'ESOCKETTIMEDOUT' || err.code === 'ETIMEDOUT' ) { //request timeout - return res.status(504).end('proxy ' + agentUrl +' timeout'); + return _sendStatus(res, 504, 'proxy ' + agentUrl +' timeout'); } onError(err, agentUrl); }); @@ -204,7 +212,7 @@ module.exports = function doProxy(options) { if (err) { const path = req.path; slogger.error('proxy ' + path +' failed:', err); - return res.status(502).end('proxy ' + path +' failed: ' + err); + return _sendStatus(res, 502, 'proxy ' + path +' failed: ' + err); } if (!backUrl) { return next(); diff --git a/package.json b/package.json index 8f39783..a937d09 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "http-request-proxy", - "version": "0.3.0", + "version": "0.4.0", "description": "The middleware for proxying request in express", "main": "index.js", "directories": {