title: Fetch image in React from Node.js request
body: <p>When needed, React asks for an image using Superagent : </p>
  
  <pre><code>exports.getImgFromSection=function(id,request){
      request
         .get('/img/'+id)
         .end((error, response) =&gt; {
             if (!error &amp;&amp; response) {
                 console.log(response.file);
             } 
             else {
                 console.log('There was an error fetching server', error);
             }
         })
  </code></pre>
  
  <p>}</p>
  
  <p>Node.js answers this way : </p>
  
  <pre><code>app.get("/img/:id",function(req, res){ 
     // check if exists and then
          res.sendFile(path.join(__dirname, './data/img/'+req.params['id']+'.png'));
  });
  </code></pre>
  
  <p>But I don't know how to get the image in React.</p>
  
  <p><code>console.log(response.file)</code> is undefined.</p>
  
  <p><code>console.log(response.files[0])</code> is undefined.</p>
  
  <p><code>console.log(response.body)</code> is null.</p>
  
  <p><code>console.log(response)</code> gives me :</p>
  
  <p><a href="https://i.stack.imgur.com/6bdZ9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6bdZ9.png" alt="console.log(response)"></a></p>
  
  <p>How do I get the image in a var ? Thank you.</p>
  
  <p><strong>SOLUTION :</strong> </p>
  
  <p>In node.js :</p>
  
  <pre><code>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);
      }); 
  </code></pre>
  
  <p>React : </p>
  
  <pre><code>request
         .get('/img/'+imgID)
         .end((error, response) =&gt; {
          if (!error &amp;&amp; response) {
              this.setState({img1:response.text})
          } else {
              console.log('There was an error fetching server', error);
          }
         })
  </code></pre>