从Node.js请求在React中获取图像 [英] Fetch image in React from Node.js request

查看:66
本文介绍了从Node.js请求在React中获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必要时,React使用Superagent询问图像:

When needed, React asks for an image using 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这样回答:

Node.js answers this way :

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

但是我不知道如何在React中获得图像.

But I don't know how to get the image in React.

console.log(response.file)未定义.

console.log(response.files [0])未定义.

console.log(response.body)为空.

console.log(响应)给我:

如何在var中获取图像?谢谢.

How do I get the image in a var ? Thank you.

解决方案:

在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);
        }
       })

推荐答案

我正在使用axios(但这将是相似的),这就是我获取图像的方式.

I am using axios (but it will be similar) this is how I get my images.

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

我认为响应类型在这里很重要.....但是我有节点将其作为流发送(因为我正在从mongo中检索……)

I think the response type is the important thing here.....but I have node sending it as a stream (as I am retrieving from mongo etc....)

这篇关于从Node.js请求在React中获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆