我正在请求一个index.djvu,它按ID触发对文档的请求。 index.djvu触发的请求ID是Base64编码的,例如 document/page_1_1_1_k21g_MjE4MGstMTAvMTE=.djvu
,其中id是 MjE4MGstMTAvMTE=
。
在发送请求之前,我需要对ID进行编码,例如encodeURIComponent('MjE4MGstMTAvMTE=')
。
如何控制index.djvu触发的请求?
我的代码如下
var http = require('http');
var httpProxy = require('http-proxy');
var HttpProxyRules = require('http-proxy-rules');
var proxyRules = new HttpProxyRules({
rules: {
// This requests response index further requests explained
'.*/document': 'https://api.service.xxx/document/index.djvu?archive=21&id=2180k-10/11'
},
default: 'https://api.service.xxx/document'
});
var proxy = httpProxy.createProxyServer({
secure: false
});
proxy.on('proxyReq', function (proxyReq, req, res, options) {
proxyReq.setHeader('Authorization', 'Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
var server = {};
server.httpServer = http.createServer(function (req, res) {
var target = proxyRules.match(req);
if (target) {
return proxy.web(req, res, {
target: target
});
}
});
server.init = () => {
server.httpServer.listen(9000, () => {
console.log('\x1b[36m%s\x1b[0m', 'The HTTP server is running on port 9000');
});
}
server.init();
server.httpServer.on('error', function (err) {
console.log('Error http-server\n', JSON.stringify(err));
});
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('Status: ' + proxyRes.statusCode + ' ' + proxyRes.statusMessage);
proxyRes.on('data', function (chunk) {
console.log('Body: ' + chunk.toString('utf8'));
});
console.log('Headers received from api: ', JSON.stringify(proxyRes.headers, true, 2));
});
感谢所有帮助
答案 0 :(得分:0)
经过数小时的战斗,问题解决了;)
var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var proxy = httpProxy.createProxyServer({
target: 'https://api.xxxxxxxxxxxxxx.xxx',
secure: false
}).listen(9000);
proxy.on('proxyReq', function (proxyReq, req, res, options) {
proxyReq.setHeader('Authorization', 'Bearer xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx');
var url_parts = url.parse(req.url);
var str = url_parts.pathname;
var query = url_parts.search;
if (str) {
var path = str.split("_");
urlstring = {
page_: path[0],
vers: path[1],
subdoc: path[2],
page: path[3],
archive: path[4],
enc_id: path[5]
}
}
var rewritedPath;
if (str.includes('route')) {
rewritedPath = '/xxx' + str;
} else if (str.includes('route')) {
var index = '/xxx' + str + query;
rewritedPath = index;
} else {
var page = 'xxx' + urlstring.page_ + '_' + urlstring.vers + '_' + urlstring.subdoc + '_' + urlstring.page + '_' + urlstring.archive + '_' + encodeURIComponent(urlstring.enc_id);
rewritedPath = page;
}
proxyReq.path = rewritedPath;
});
proxy.on('error', function (err, req, res) {
console.log('Something went wrong.', err);
});
proxy.on('proxyRes', function (proxyRes, req, res) {
// console.log('Status: ' + req.url + ' ' + proxyRes.statusMessage);
// proxyRes.on('data', function (chunk) {
// console.log('Body: ' + chunk.toString('utf8'));
// });
// console.log('Headers: ', JSON.stringify(proxyRes.headers, true, 2));
});