How to use the json-server.router function in json-server

To help you get started, we’ve selected a few json-server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github fusor / mig-ui / mock / server.js View on Github external
// server.js
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./mock/db.json');

const middlewares = jsonServer.defaults();

server.use(middlewares);
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});
github cloudfroster / react-workflow / server / remote / remoteServer.js View on Github external
const bodyParser = require('body-parser')
const jsonServer = require('json-server')
// Returns an Express server
const app = express()

app.set('port', (process.env.PORT || 5001))

// express middleware
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())

// Set default middlewares (logger, static, cors and no-cache)
app.use(jsonServer.defaults())
app.use('/api', jsonServer.router(path.join(__dirname, './api/db.json')))

// start server
app.listen(app.get('port'), () => {
  /* eslint-disable no-console */
  console.log(chalk.cyan(`The remote server is running at http://localhost:${app.get('port')}`))
  if (process.send) {
    process.send('online')
  }
})
github kosson / javascript-invat-eu-inveti-si-tu / promises / PRACTICE / getJSON.js View on Github external
var jsonServer = require('json-server'),
    server = jsonServer.create(),
    router = jsonServer.router('db.json'),
    middlewares = jsonServer.defaults(),
    XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

    server.use(middlewares);
    server.use(router);

function getJSON(url){
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();               // inițializarea obiectului XMLHttpRequest
    request.open("GET", url);                           // [request.open]   --> inițierea unui GET pe url primit ca argument

    request.onload = function(){                        // [request.onload] --> try-catch
      try{
        if(this.status === 200){                        // [this.status] dacă this.status este 200
          console.log(`Răspunsul este ${this.status}`);
          resolve(JSON.parse(this.response));           // [this.response] invocă resolve cu JSON.parse(this.response), daca raspunsul este parsabil
github RackHD / on-web-ui / scripts / tools / mock_api.js View on Github external
// Copyright 2015, EMC, Inc.

'use strict';

var jsonServer = require('json-server');

var server = jsonServer.create();

server.use(jsonServer.defaults);

server.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
server.use(jsonServer.router({
  workflows: [
    {
      id: 'Graph.Noop',
      name: 'No-Op Graph',
      tasks: [
        {
          label: 'noop-1',
          taskName: 'Task.noop'
        },
        {
          label: 'noop-2',
          taskName: 'Task.noop',
          waitOn: {
            'noop-1': 'finished'
          }
        },
github techiediaries / fake-api-jwt-json-server / server.js View on Github external
const fs = require('fs')
const bodyParser = require('body-parser')
const jsonServer = require('json-server')
const jwt = require('jsonwebtoken')

const server = jsonServer.create()
const router = jsonServer.router('./database.json')
const userdb = JSON.parse(fs.readFileSync('./users.json', 'UTF-8'))

//server.use(bodyParser.urlencoded({extended: true}))
//server.use(bodyParser.json())
server.use(jsonServer.defaults());

const SECRET_KEY = '123456789'

const expiresIn = '1h'

// Create a token from a payload 
function createToken(payload){
  return jwt.sign(payload, SECRET_KEY, {expiresIn})
}

// Verify the token 
github coryhouse / pluralsight-redux-starter / tools / apiServer.js View on Github external
This uses json-server, but with the module approach: https://github.com/typicode/json-server#module
Downside: You can't pass the json-server command line options.
Instead, can override some defaults by passing a config object to jsonServer.defaults();
You have to check the source code to set some items.
Examples:
Validation/Customization: https://github.com/typicode/json-server/issues/266
Delay: https://github.com/typicode/json-server/issues/534
ID: https://github.com/typicode/json-server/issues/613#issuecomment-325393041
Relevant source code: https://github.com/typicode/json-server/blob/master/src/cli/run.js
*/

/* eslint-disable no-console */
const jsonServer = require("json-server");
const server = jsonServer.create();
const path = require("path");
const router = jsonServer.router(path.join(__dirname, "db.json"));

// Can pass a limited number of options to this to override (some) defaults. See https://github.com/typicode/json-server#api
const middlewares = jsonServer.defaults();

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares);

// To handle POST, PUT and PATCH you need to use a body-parser. Using JSON Server's bodyParser
server.use(jsonServer.bodyParser);

// Simulate delay on all requests
server.use(function(req, res, next) {
  setTimeout(next, 2000);
});

// Declaring custom routes below. Add custom routes before JSON Server router
github mjzhang1993 / react-router4-template / server / index.js View on Github external
const jsonServer = require('json-server');
const ip = require('ip').address();
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const createDB = require('./db.js');
const mounted = require('./route');
const DB = createDB();
const router = jsonServer.router(DB);

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

mounted(server, DB);
server.use(router);

server.listen(
   {
      host: ip,
      port: 3167
   },
   function() {
      console.log(`JSON Server is running in http://${ip}:3167`);
   }
);
github typicode / jsonplaceholder / src / app.js View on Github external
const jsonServer = require('json-server')
const clone = require('clone')
const data = require('../data.json')

const app = jsonServer.create()
const router = jsonServer.router(clone(data), { _isFake: true })

app.use((req, res, next) => {
  if (req.path === '/') return next()
  router.db.setState(clone(data))
  next()
})

app.use(jsonServer.defaults({
  logger: process.env.NODE_ENV !== 'production'
}))

app.use(router)

module.exports = app
github pharindoko / json-serverless / src / core.js View on Github external
async function initializeLayers() {
  const adapter = await low(storage);
  const router = jsonServer.router(adapter);
  const middlewares = jsonServer.defaults({ readOnly: appConfig.readOnly });
  return { middlewares, router };
}

json-server

> [!IMPORTANT] > Viewing alpha v1 documentation – usable but expect breaking changes. For stable version, see [here](https://github.com/typicode/json-server/tree/v0)

SEE LICENSE IN ./LICENSE
Latest version published 3 months ago

Package Health Score

83 / 100
Full package analysis