我正在尝试使用 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 那样工作?