nodejs express server img src
To display an image using Node.js and the Express server, you can follow these steps:
First, install the necessary dependencies by running the following command in your project directory:
npm install express
Create a new JavaScript file, for example,
server.js
, and require the Express module:javascript const express = require('express');
Create an instance of the Express application:
javascript const app = express();
Define a route that will handle the request to display the image. In this example, we'll assume that the image file is located in the
public
directory and is namedimage.jpg
:javascript app.get('/image', (req, res) => { res.sendFile(__dirname + '/public/image.jpg'); });
Set up the server to listen on a specific port. For example, to listen on port 3000, you can add the following code:
javascript app.listen(3000, () => { console.log('Server listening on port 3000'); });
To start the server, run the following command in your terminal:
node server.js
Now, you can access the image by visiting
http://localhost:3000/image
in your browser.
These steps will allow you to create a Node.js Express server that serves an image file to be displayed in a browser.