How to use the json-server.bodyParser 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 kiranz / just-api / test / api / server.js View on Github external
// req.file is the `file_name` file
    // req.body will hold the text fields, if there were any
    //returns json {
    //  "file_size": 51938,
    //  "body": {
    //    "key1": "va1"
    //  }
    //}
    res.jsonp({'file': req.file, fields: req.body});
});

server.post('/echoMultipartBodyMultipleFileStats', upload.any(), function (req, res, next) {
    res.jsonp({files: req.files, fields: req.body});
});

server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
    next();
});

server.use(router);
server.listen(3027, () => {
    console.log('JSON Server is running')
});
github rohan-deshpande / trux / test / server.js View on Github external
connection = server.listen(port, () => {
    // set middlewares
    server.use(middlewares);

    // setup the body-parser for POST, PUT & PATCH requests
    server.use(jsonServer.bodyParser);

    // set test routes
    server.get('/profile/auth', (req, res) => {
      res.writeHead(200, 'OK', { 'Authorization': token });
      res.end(JSON.stringify(schema.profile));
    });

    // use router
    server.use(router);
  });
}
github ManageIQ / manageiq-ui-service / mock_api / server.js View on Github external
function init() {
  server.use(jsonServer.bodyParser);
  server.use(function(req, res, next) {
    if (process.env.LOG_LEVEL && process.env.LOG_LEVEL === 'debug') {
      console.log(req.body);
    }
    next();
  });

  loadDataFiles().then(function(resp) { // We load all endpoints
    return loadLocalOverrideFiles(resp);
  })
    .then(function(endpoints) { // We apply local endpoint overrides
      let uniqueURLS = 0;
      lodash.forIn(endpoints, function(data, endpointName) {
        uniqueURLS += Object.keys(data).length;
        buildRESTRoute(data, endpointName); //  This builds the rest route
      });
github lbwa / adminize / mock / server / index.js View on Github external
const Server = require('json-server')
const config = require('./config')

const PORT = process.env.PORT || 8800

// Notice: Keep correct sequences, otherwise request body would be empty object.
const server = Server.create()
const middleware = Server.defaults()
const router = Server.router()

server.use(middleware)
server.use(Server.bodyParser)

config.initConfig(server)
server.use(router)

server.listen(PORT, () => {
  console.log(`[json server]: Server is running at http://localhost:${PORT}`)
})
github benc-uk / smilr / vue / mock-api / server.js View on Github external
// Mock REST API server without database
// Uses JSON Server https://github.com/typicode/json-server
// - Ben Coleman, Dec 2018
//
const jsonServer = require('json-server')
const server = jsonServer.create()
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'db.json'))

// Pretend we're using MongoDB style ids
router.db._.id = '_id';

// Set up middleware and bodyParser for JSON
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)

// Static routes
server.get('/api', (req, res) => {
  res.send('<h1>Mock API server for Smilr is running</h1>')
})
server.get('/api/info', (req, res) =&gt; {
  res.send({ message: "Mock API server for Smilr is running"})
})

// Various routes and tricks to act like the real Smilr API
var today = new Date().toISOString().substr(0, 10)
server.use(jsonServer.rewriter({
  "/api/feedback/:eid/:tid":    "/api/feedback?event=:eid&amp;topic=:tid",
  "/api/events/filter/future":  "/api/events?start_gte="+today+"&amp;start_ne="+today,
  "/api/events/filter/past":    "/api/events?end_lte="+today+"&amp;start_ne="+today,
  "/api/events/filter/active":  "/api/events?start_lte="+today+"&amp;end_gte="+today
github ninghao / w-store-app / service / index.js View on Github external
/* eslint-disable import/no-commonjs */
const jsonServer = require('json-server')
const { dbFile } = require('./db')

const server = jsonServer.create()
const router = jsonServer.router(dbFile)
const middlewares = jsonServer.defaults()

const cart = require('./modules/cart')
const user = require('./modules/user')

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

server.use([cart, user])

router.render = (req, res) => {
  if (req.method === 'GET') {
    if (req.path === '/users') {
      const users = res.locals.data.map(item => {
        delete item.password

        return item
      })

      res.jsonp(users)

      return
    }
github rajezvelse / json-server-jwt / server.js View on Github external
var randomStr = function (length) {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i &lt; length; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}


// 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
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)

/*          DB defaults
----------------------------------------------------*/
// Set some defaults (required if your JSON file is empty)
var db = low(source, { storage: fileAsync });
db.defaults({ users: [], roles: [], password_reset_tokens: [], user_settings: [] })
  .write()


// Middleware actions
server.use((req, res, next) =&gt; {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

  //intercepts OPTIONS method
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 TommyCpp / Athena / frontend / web / src / mockend / mockend.js View on Github external
const readers = {
  11: "12314",
  12: "12234"
};

const admins = {
  16: "1111"
};

const superAdmins = {
  10: "11111"
};

server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
  res.header("access-control-expose-headers",
    "X-AUTHENTICATION"
  );
  next()
});
server.get('/user', (req, res) => {
  let token = req.header('X-AUTHENTICATION');
  let id = token.substr(token.length - 2);
  res.redirect(`/users/${id}`);
});
server.post('/login', (req, res) => {
  let id = req.body["id"];
  let token = "O8Hp9YH98h98YO89y90T0F87feG80F";
  if (readers.hasOwnProperty(id) && readers[id] === req.body['password']) {
    res.set({

json-server

[![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)

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

Package Health Score

88 / 100
Full package analysis