节点http-proxy:请求主体的asynchronous修改
我需要asynchronous修改请求主体。 一些沿着这条线:
proxy.on('proxyReq', function(proxyReq, req, res, options) { if(req.body) { new Promise(function(resolve){ setTimeout(function() { // wait for the db to return 'use strict'; req.body.text += 'test'; let bodyData = JSON.stringify(req.body); proxyReq.setHeader('Content-Type','application/json'); proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); // stream the content proxyReq.write(bodyData); resolve(); },1); }); } });
当我运行这个我得到的错误说,不能modfiy头一旦设置。 这是有道理的。
我如何才能停止发送请求,直到我准备好了? 我已经看过从proxyReq中删除各种监听器,但没有成功。
通过查看源代码 @ – )似乎是不可能的,因为proxyReq
事件被发送,然后代码继续。
如果它会等待一个承诺,那么这将是可能的(如果你还愿意的话)。
在这个库上的一个最小叉可以是例如:
// Enable developers to modify the proxyReq before headers are sent proxyReq.on('socket', function(socket) { if(server) { server.emit('proxyReq', proxyReq, req, res, options); } }); (proxyReq.proxyWait || Promise.resolve()) .then( ... // rest of the code inside the callback
接着
proxy.on('proxyReq', function(proxyReq, req, res, options) { if(req.body) { proxyReq.proxyWait = new Promise(function(resolve){ setTimeout(function() { ...
但根据您的使用情况,也可能有其他解决scheme。 例如,考虑是否真的有必要使用这个代理库。 它你也可以直接使用http,你可以在这里控制事件和callback。