Bryan
Broski blog

Broski blog

How to create a mock-server inside Angular

Photo by Nana Fuzimi on Unsplash

How to create a mock-server inside Angular

Bryan's photo
Bryan
·Aug 6, 2022·

2 min read

Introduction

If you want créate your front-end project without the back-end you need to use a mock. You can create a mock who acts as a true back end. I want to share this solution with you.

Pre-requisites

**Angular project

ng g myProject

Json-server

npm install json-server --save-dev

Nodemon

npm install nodemon --save-dev

Let's do it

For this example my name of the project is anime-shop

Create a server folder

Capture d’écran 2022-08-06 à 12.15.20.png

Create your mock JSON

Inside your folder server there are files that are :

Capture d’écran 2022-08-06 à 12.13.58.png

animes.json

{
  {
    "name" : "Dragon ball Z",
   " type" : " Action"
  },
  {
    "name" : "Naruto",
   " type" : " Action"
  },
}

index.json

const getAnimes = require('./json/animes.json')

module.exports = {
  getAnimes: getAnimes
}

server.js

const JSON server = require('json-server')
const middleware = jsonServer.defaults()
const server = jsonServer.create()

server.use(middleware);
server.use(jsonServer.bodyParser);

const animesData = require("./data/anime")

server.get('/api/animes', (req, res, nex) => {
  res.status(200).send(animesData.getAnimes)
})

server.listen(3000, () => {
  console.log('Fake server run on port 3000')
})

Change your package.json

Add "mock-server": "nodemon server/server.js --ext js,ts,json,html"

{
  "name": "anime-shop",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "mock-server": "nodemon server/server.js --ext js,ts,json,html"
  },

Finaly

Run your json-serveur

npm run mock-server

Test your URL

http://localhost:3000/api/animes
 
Share this