Fetch image in React from Node.js request

帅比萌擦擦* 提交于 2021-02-19 08:56:14

问题


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

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

console.log(response.file) is undefined.

console.log(response.files[0]) is undefined.

console.log(response.body) is null.

console.log(response) gives me :

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

SOLUTION :

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

React :

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

回答1:


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

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....)




回答2:


SOLUTION :

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

React :

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



回答3:


Use Axios package to fetch a POST Request in React. https://github.com/axios/axios

https://github.com/axios/axios

you need to send a request to fetch image or post image. Just an Example.

This is a function in React.

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


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

    }

This will send the request to Nodejs here:

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>
    `;

This is how Fetch request is also done, but fetching part will be in React Code.

Anyways read the Axios Documentation. it will be having various examples about it.



来源:https://stackoverflow.com/questions/51473585/fetch-image-in-react-from-node-js-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!