How to display Image in Postman using Express ?
Postman is a powerful tool for testing APIs, but when it comes to displaying images, it can be a little bit tricky. This article, the process of setting up an Express server to serve images and accessing them using Postman.
Prerequisites:
Steps to display Image in Postman:
Step 1: Image Preparation
Place your image file (e.g., ‘image.jpg’) inside the ‘images’ directory.
Step 2: Install Dependencies
Open your terminal, navigate to the project directory, and install the required dependencies.
npm init -ynpm install express
Step 3: Create the Express.js Server by Creating a file named “server.js“.
Project Structure:
Example: Write the following code in server.js file.
Javascript
const express = require( 'express' ); const path = require( 'path' ); const app = express(); // Serve static files from the 'images' directory app.use( '/images' , express.static(path.join(__dirname, 'images' ))); // Define a route to handle API requests app.get( '/api/images/:imageName' , (req, res) => { const imageName = req.params.imageName; // Construct the file path based on the requested image name const imagePath = path.join(__dirname, 'images' , imageName); // Check if the file exists if (require( 'fs' ).existsSync(imagePath)) { // If the file exists, send it as a response res.sendFile(imagePath); } else { // If the file doesn't exist, return a 404 error res.status(404).send('Image not found'); } }); // Start the server on port 3000 const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); |
Step to test the application
Step 1: Start the Server
Run the server using the following command:
node server.js
Step 2: Test with Postman
Open Postman and create a new request make a GET request to:
http://localhost:3000/api/images/geek.jpg (replace 'geek.jpg' with the actual image name).
Output: If everything is set up correctly, you should receive the image as a response. If not, double-check the image path, file name, and server configuration.
Contact Us