Skip to content

201 JSON Server

zarlex edited this page Mar 6, 2017 · 1 revision

Setting up the json-server

At first add the json-server to our package.json as a development dependency.

npm install json-server --save-dev

Then we create a new folder in our root folder called json-server In this folder we create two files, json-server.js and seed.json In the json-server.jswe set up a basic server configuration

var jsonServer = require('json-server');
var server = jsonServer.create();
var seed = require('./seed.json'); // require our seed file to seed our database with the data on start up
var router = jsonServer.router(seed); // use the required seed file to set up the API 
var middlewares = jsonServer.defaults();

server.use(middlewares);
// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser);
server.use(function (req, res, next) {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now(); // set createdAt and modifiedAt timestep for all POST reqeusts
    req.body.modifiedAt = Date.now();
  }
  if (req.method === 'PUT') {
    req.body.modifiedAt = Date.now();// update modifiedAt timestep for all PUT reqeusts
  }
  // Continue to JSON Server router
  next();
});

server.use('/api', router); // '/api' is our base api path
server.listen(3000, function () {
  console.log('JSON Server is running')
});

Our seed.json provides some default heroes. Those heroes are available when the server is started. When we stop our server all changes that where done by making PUT, POST, DELETE requests are lost. We don't want to start with a empty database on every startup so thats why we have this seed file

{
  "heroes": [
    {"id": 11, "name": "Mr. Nice"},
    {"id": 12, "name": "Narco"},
    {"id": 13, "name": "Bombasto"},
    {"id": 14, "name": "Celeritas"},
    {"id": 15, "name": "Magneta"},
    {"id": 16, "name": "RubberMan"},
    {"id": 17, "name": "Dynama"},
    {"id": 18, "name": "Dr IQ"},
    {"id": 19, "name": "Magma"},
    {"id": 20, "name": "Tornado"}
  ]
}

When we start our server

npm run server

we have our first endpoint called api/heroes. When you open your browser and go to http://localhost:3000/api/heroes you will get a JSON object with all those heroes

Clone this wiki locally