Почему ответ с сервера прилетает не картинка
Когда отправляю запрос на получение картинки, ответом прилетяют кряказяблы
const { Router } = require('express');
const request = require('request-promise')
const weatherRouter = Router();
const key = '27dd86c06ee0058cdea528fcf006a5df';
weatherRouter.get('/',(req,res) => {
const city = req.query.q;
const icon = req.query.icon;
request(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}`)
.then(
body => {
if(icon){
const bodyParse = JSON.parse(body)
request(`http://openweathermap.org/img/w/${bodyParse.weather[0].icon}.png`) // imgURL
.then(image => res.set('Content-Type', 'image/png').send(image))
} else {
res.send(body)
}
}
)
})
module.exports = weatherRouter;
Ответы (1 шт):
Автор решения: nörbörnën
→ Ссылка
Не нужно работать с бинарными данными как с текстом.
Правильное решение очень простое - перенаправить stream ответа openweathermap.org в stream ответа "нашего сервера":
weatherRouter.get('/',(req, res) => {
const city = req.query.q;
const needIcon = req.query.icon;
request(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}`)
.then((resp) => {
const weatherData = JSON.parse(resp);
const icon = weatherData.weather && weatherData.weather[0] ? weatherData.weather[0].icon : undefined;
if (needIcon === 1 && icon) {
request(`http://openweathermap.org/img/w/${icon}.png`).pipe(res);
} else {
res.json(weatherData);
}
})
.catch((err) => {
console.log(err);
res.status(406).json({ error: `${err}` });
});
});