在管道之前编辑响应标题 [英] Edit response headers before piping
本文介绍了在管道之前编辑响应标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
app.use('/ api',function(req,res){
var url = rewriteUrl(req.url);
var newReq = request url,function(error){
if(error){
logError(error);
}
});
req.pipe(newReq ).pipe(res);
});
我的问题是,API服务器的响应包含一堆我想要删除的不需要的标题。如何从 newReq
的回复中删除标题,然后再将其导入 res
?
解决方案
使用请求
模块,目前没有办法(AFAIK)有回调而不是缓冲服务器响应。所以这里是如何使用内置的 http.request
来实现的:
app.use('/ api',function(req,res){
var url = rewriteUrl(req.url);
var newReq = http.request ,function(newRes){
var headers = newRes.headers;
//修改`headers`这里...
res.writeHead(newRes.statusCode ,标题);
newRes.pipe(res);
})。on('error',function(err){
res.statusCode = 500;
res.end ();
});
req.pipe(newReq);
});
I have a small proxy for certain requests in Express. Using the request library, I have fairly concise code:
app.use('/api', function(req, res) {
var url = rewriteUrl(req.url);
var newReq = request(url, function(error) {
if (error) {
logError(error);
}
});
req.pipe(newReq).pipe(res);
});
My problem is that the response from the API server contains a bunch of unwanted headers that I want to remove. How can I remove the headers from the response of newReq
before piping it to res
?
解决方案
With the request
module, there currently isn't a way (AFAIK) to have a callback and not buffer the server response. So here is how you might do it with the built-in http.request
:
app.use('/api', function(req, res) {
var url = rewriteUrl(req.url);
var newReq = http.request(url, function(newRes) {
var headers = newRes.headers;
// modify `headers` here ...
res.writeHead(newRes.statusCode, headers);
newRes.pipe(res);
}).on('error', function(err) {
res.statusCode = 500;
res.end();
});
req.pipe(newReq);
});
这篇关于在管道之前编辑响应标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文