Some doubts in expressjs related to image output

 So here is my code

 const response = await fetch(`http://example.com\?write=Hi+Pls+Help`); // when we go here shows a png image
    const headers = { "Content-Type": "image/png" };

  //set status code and headers
  res.writeHead(200, headers);
response.body.pipe(res);

And it just timesout if I stay on the web

I am trying to display another image from a backend server of mine that is fully dynamic

Please help me a way for it


It's unclear from your code snippet what exactly you are trying to achieve, but it seems like you are trying to fetch a PNG image from a remote server and display it in the response of your Express.js server.

If that's the case, your code looks mostly correct, but there are a few things you should consider:

  1. The URL you are fetching (http://example.com\?write=Hi+Pls+Help) is not a valid URL. You have a backslash (\) instead of a forward slash (/) after the domain name. Make sure you are fetching the correct URL.

  2. You should check the response status code and handle errors. For example, if the remote server returns a 404 error, you should not try to display the image.

  3. Make sure you are properly closing the response stream after piping it to the Express.js response. You can do this by adding a .on('end', () => res.end()) callback after response.body.pipe(res).

Here's an updated version of your code with these considerations in mind:

javascript
const fetch = require('node-fetch'); const express = require('express'); const app = express(); app.get('/', async (req, res) => { try { const response = await fetch('http://example.com/?write=Hi+Pls+Help'); if (!response.ok) { throw new Error('Failed to fetch image'); } const headers = { 'Content-Type': 'image/png' }; res.writeHead(200, headers); response.body.pipe(res).on('end', () => res.end()); } catch (error) { console.error(error); res.status(500).send('Failed to fetch image'); } }); app.listen(3000, () => { console.log('Server listening on port 3000'); });

This code fetches the image from http://example.com/?write=Hi+Pls+Help, checks if the response is successful, sets the content type header to image/png, pipes the response body to the Express.js response, and closes the response stream when done. If there is an error, it sends a 500 response with an error message.

Comments