【发布时间】:2021-05-18 00:53:23
【问题描述】:
我正在尝试使用 axios 从另一个 Node 应用程序 [通过 Node http get request] 获取图片。 问题是,当我使用 axios 时,我得到了错误的文件格式,当我保存它时,它没有 看看石灰一张图片...当我使用http get时,我得到了一张完美的图片,并且保存得很好。
- 获取图片的工作代码:
接收方:
var data = new Stream.Transform();
res.on('data', function(chunk) {
console.log(typeof chunk)
data.push(chunk);
});
res.on('end', function() {
fs.writeFileSync('event.png', data.read());
});
发件人:
export const getImage = (req, res) => {
const pathToImage = 'C:/dev/server/images/event.jpg';
const img = fs.readFileSync(pathToImage);
res.writeHead(200, {'Content-Type': 'blob' });
res.end(img, 'binary');
}
- axios(无效代码):
axios.get(url)
.then((response: AxiosResponse)=>{
// save picture locally:
let data = new Stream.Transform();
data.push(response.data);
fs.writeFileSync('event.jpg', data.read());
})
.catch((error: AxiosError) => {
console.log(error.message);
})
你知道为什么 axios 不像 http 那样工作吗?
【问题讨论】:
-
可以用邮递员获取图片吗?
-
是的,正如我所说,我可以使用简单的 http get 获取它。
标签: node.js axios http-get node-rest-client