我已经在Node中组建了一个代理服务器,它需要能够通过tls隧道传输https请求并且一切正常。使用以下两个软件包非常容易设置:proxy,https-proxy-agent。我的问题是我试图使用connect作为中间件层捕获HAR文件,我收到以下错误:
_http_outgoing.js:357
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.writeHead (_http_server.js:180:21)
at ClientRequest.<anonymous> (/.../node_modules/proxy/proxy.js:233:11)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at Socket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
就像下面一样简单,只有当我使用connect并通过本地浏览器进行代理时才会发生这种情况(此代理实际上与BrowserStackLocal一起使用)。当我从本地机器浏览器以外的任何地方传递代理时,就好像它甚至不知道中间件存在。
所以基本上,我只需要让连接在这种情况下工作,我不确定是否需要暂停某些内容和恢复,或者什么......任何想法都会受到高度赞赏。基本代码如下:
const path = require('path');
const http = require('http');
const proxy = require('proxy');
const Agent = require('https-proxy-agent');
const connect = require('connect');
const har = require('./har');
const middleware = connect();
middleware.use(har({
harOutputDir: path.resolve(process.cwd(), 'har/')
}));
const server = proxy(http.createServer(middleware));
server.agent = new Agent('http://localhost:8081');
server.listen(8081)
谢谢!
编辑:只是注意:har中间件根本没有修改标题。
答案 0 :(得分:1)
similarColors
暂时没有维持。构建没有通过,最后一次提交不通过测试。您提供的堆栈跟踪源来自here in Line 233 - 错误的库代码。
编写类似的代理是微不足道的。以下代码说明了如何创建一个。
proxy
使用您自己的自定义代理的代码如下所示:
const http = require('http');
const urlP = require('url');
const proxiedServer = 'http://localhost:8888';
// Proxy server
http.createServer((req, res) => {
console.log(`Proxy: Got ${req.url}`);
const _r = http.request(
Object.assign(
{},
urlP.parse(proxiedServer),
{
method: req.method,
path: req.url
}
),
_res => {
res.writeHead(_res.statusCode, _res.headers);
_res.pipe(res);
}
);
req.pipe(_r);
}).listen(3124, () => {
console.log("Listening on 3124");
});
// Regular server. Could be Express
http.createServer((req, res) => {
console.log('Proxied server: ', req.url);
let b = '';
req.on('data', c => {
b += c;
});
req.on('end', () => {
console.log('Proxied server: ', b);
});
res.writeHead(200);
res.end('ok');
}).listen(8888, () => {
console.log('proxied server listening on 8888');
});