How to create a mock API in localhost using Node.js and Express.js

--

  1. Run npm init command to initialize a new Node.js project
  2. Run npm install --save expressto install Express.js
  3. Create a file named mockapi.js and open it
  4. Enter the following code and save it
const express = require('express');
const app = express();
const port = 3000;
app.get('/*', (req, res) => {
res.json({message: 'Hello World, from express'});
});
app.put('/*', (req, res) => {
res.json({message: 'Hello World, from express'});
});
app.post('/*', (req, res) => {
res.json({message: 'Hello World, from express'});
});
app.delete('/*', (req, res) => {
res.json({message: 'Hello World, from express'});
});
app.patch('/*', (req, res) => {
res.json({message: 'Hello World, from express'});
});
app.listen(port, () => console.log(`Hello world, app is listening on port ${port}!`))

5. Run node mockapi.js command to start the mock API

6. Run curl -X GET localhost:3000 to invoke the API

--

--

Binod Karunanayake

PhD Candidate @RMIT University | Former Software Engineer @WSO2 | BSc Engineering (Hons) University of Moratuwa