Получить изображение в React из запроса Node.js

При необходимости React запрашивает образ с помощью Superagent:

exports.getImgFromSection=function(id,request){
    request
       .get('/img/'+id)
       .end((error, response) => {
           if (!error && response) {
               console.log(response.file);
           } 
           else {
               console.log('There was an error fetching server', error);
           }
       })

}

Node.js отвечает так:

app.get("/img/:id",function(req, res){ 
   // check if exists and then
        res.sendFile(path.join(__dirname, './data/img/'+req.params['id']+'.png'));
});

Но я не знаю, как получить изображение в React.

console.log(response.file) не определено.

console.log(response.files[0]) не определено.

console.log(response.body) равно нулю.

console.log(response) дает мне:

console.log(ответ)

Как получить изображение в var? Спасибо.

РЕШЕНИЕ:

В node.js:

var img = fs.readFile('./data/imagesUploaded/image.png', function (err, data) {
        var contentType = 'image/png';
        var base64 = Buffer.from(data).toString('base64');
        base64='data:image/png;base64,'+base64;
        res.send(base64);
    }); 

Реагировать:

request
       .get('/img/'+imgID)
       .end((error, response) => {
        if (!error && response) {
            this.setState({img1:response.text})
        } else {
            console.log('There was an error fetching server', error);
        }
       })

person Pol Grisart    schedule 23.07.2018    source источник


Ответы (3)


Я использую axios (но это будет похоже), так я получаю свои изображения.

  const res = await axios.get(`/image/${imageId}`, {
    responseType: 'arraybuffer'
  });
  const imgFile = new Blob([res.data]);
  const imgUrl = URL.createObjectURL(imgFile);

Я думаю, что тип ответа здесь важен..... но у меня есть узел, отправляющий его как поток (поскольку я получаю данные из монго и т.д....)

person Intellidroid    schedule 23.07.2018

РЕШЕНИЕ :

В node.js:

var img = fs.readFile('./data/imagesUploaded/image.png', function (err, data) {
        var contentType = 'image/png';
        var base64 = Buffer.from(data).toString('base64');
        base64='data:image/png;base64,'+base64;
        res.send(base64);
    }); 

Реагировать:

request
       .get('/img/'+imgID)
       .end((error, response) => {
        if (!error && response) {
            this.setState({img1:response.text})
        } else {
            console.log('There was an error fetching server', error);
        }
       })
person Pol Grisart    schedule 24.07.2018

Используйте пакет Axios для получения запроса POST в React. https://github.com/axios/axios

https://github.com/axios/axios

вам нужно отправить запрос на получение изображения или опубликовать изображение. Просто Пример.

Это функция в React.

 async sendEmail(name,interest,email,phone,message){


          const form = await axios.post('/api/form',{
            name,
            interest,
            email,
            phone,
            message
        })

    }

Это отправит запрос в Nodejs здесь:

app.post('/api/form',(req,res)=>{

        console.log(req.body);
        console.log(123);
        const output = `
    <p> You have a  Request</p>
        <h3> Contact Details </h3>
        <ul>
            <li> Name : ${req.body.name}</li>
            <li> Interest : ${req.body.interest}</li>
            <li> Email : ${req.body.email}</li>
            <li> Email : ${req.body.phone}</li>
            <li> Email : ${req.body.message}</li>
        </ul>
    `;

Таким же образом выполняется запрос на выборку, но часть выборки будет в коде React.

В любом случае прочитайте документацию Axios. это будет иметь различные примеры об этом.

person codemt    schedule 23.07.2018
comment
Superagent эквивалентен Axios, поэтому мою проблему он не решит. Кроме того, в вашем примере показана форма с текстовыми данными, и мне нужно простое изображение из Node.js. - person Pol Grisart; 23.07.2018