How to use json-server - 10 common examples

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
const jsonServer = require('json-server'); // eslint-disable-line no-undef
const middlewares = jsonServer.defaults();
const server = jsonServer.create();
const protocol = 'http';
const host = 'localhost';
const port = 3000;
const endpoint = `${protocol}://${host}:${port}`;
const schema = {
  'posts': [
    {
      'title': 'baz',
      'author': 'foo',
      'id': 1
    },
    {
      'title': 'qux',
      'author': 'bar',
      'id': 1
    }
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
const jsonServer = require('json-server');
const fs = require('fs');
const url = require('url');
const lodash = require('lodash');
const glob = require('glob');
const path = require('path');

let server = jsonServer.create();
let router = jsonServer.router();
let middlewares = jsonServer.defaults();

init();

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
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 naholyr / json-server-gui / src / server.js View on Github external
}
if (indexOfMiddleware < app._router.stack.length) {
  app._router.stack[indexOfMiddleware] = new RouterLayer("/", {
    "sensitive": app._router.caseSensitive,
    "strict": false,
    "end": false
  }, serveStatic(path.resolve(appDir, "public")));
  console.log("Serve static directory:", path.resolve(appDir, "public"));
}

// DB file
app.low.path = path.resolve(appDir, "db.json");
if (!fs.existsSync(app.low.path)) {
  fs.writeFileSync(app.low.path, "{}");
}
app.low.db = require(app.low.path);

// Now the real HTTP server
var server = http.createServer(app);
app.port = process.env.PORT || 26080;

server.listen(app.port);

server.on("listening", function () {
  console.log("Server ready:", this.address());
});

// Emit on each request
function ping (name, req) {
  if (req.method !== "GET") {
    setTimeout(function () {
      process.emit("data-update");
github naholyr / json-server-gui / src / server.js View on Github external
"strict": false,
    "end": false
  }, serveStatic(path.resolve(appDir, "public")));
  console.log("Serve static directory:", path.resolve(appDir, "public"));
}

// DB file
app.low.path = path.resolve(appDir, "db.json");
if (!fs.existsSync(app.low.path)) {
  fs.writeFileSync(app.low.path, "{}");
}
app.low.db = require(app.low.path);

// Now the real HTTP server
var server = http.createServer(app);
app.port = process.env.PORT || 26080;

server.listen(app.port);

server.on("listening", function () {
  console.log("Server ready:", this.address());
});

// Emit on each request
function ping (name, req) {
  if (req.method !== "GET") {
    setTimeout(function () {
      process.emit("data-update");
    }, 100);
  }
  process.emit("request", req.method, req.url, req.body);
}
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

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 1 month ago

Package Health Score

88 / 100
Full package analysis