如何解决在Node JS中管道远程文件以寻找替代方法
我正在使用request
模块,现在不推荐使用。无需存储在服务器中就可以通过管道传输远程文件。因此,寻找与Node-fetch,GOT,Axios等功能相同的替代解决方案。
import request from 'request';
(req,res) {
return request(`http://files.com/image.jpg`)
.on('error',(err) => {
log.error('error fetching img url: %O',err);
res.status(500).end('error serving this file');
})
.on('response',(urlRes) => {
if (urlRes.statusCode === 304) return;
urlRes.headers['content-disposition'] = `inline;filename="${slug}"`;
})
.pipe(res);
}
解决方法
我刚刚用node-fetch
模块尝试过这种方法,它可以工作。但是,它不会像request
模块中那样通过管道传递响应标头。因此,我们需要手动设置所需的标头。
import fetch from 'node-fetch';
(req,res) {
fetch('http://files.com/image.jpg').then((response) => {
res.set({
'content-length': response.headers.get('content-length'),'content-disposition': `inline;filename="${slug}"`,'content-type': response.headers.get('content-type'),})
response.body.pipe(res);
response.body.on('error',() => {}) // To handle failure
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。