Change port json-server

Get a full fake REST API with zero coding in less than 30 seconds [seriously]

Created with { res.jsonp[req.query] }] // 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[[req, res, next] => { if [req.method === 'POST'] { req.body.createdAt = Date.now[] } // Continue to JSON Server router next[] }] // Use default router server.use[router] server.listen[3000, [] => { console.log['JSON Server is running'] }]

Access control example

const jsonServer = require['json-server'] const server = jsonServer.create[] const router = jsonServer.router['db.json'] const middlewares = jsonServer.defaults[] server.use[middlewares] server.use[[req, res, next] => { if [isAuthorized[req]] { // add your authorization logic here next[] // continue to JSON Server router } else { res.sendStatus[401] } }] server.use[router] server.listen[3000, [] => { console.log['JSON Server is running'] }]

Custom output example

To modify responses, overwrite router.render method:

// In this example, returned resources will be wrapped in a body property router.render = [req, res] => { res.jsonp[{ body: res.locals.data }] }

You can set your own status code for the response:

// In this example we simulate a server side error response router.render = [req, res] => { res.status[500].jsonp[{ error: "error message here" }] }

Rewriter example

To add rewrite rules, use jsonServer.rewriter[]:

// Add this before server.use[router] server.use[jsonServer.rewriter[{ '/api/*': '/$1', '/blog/:resource/:id/show': '/:resource/:id' }]]

Mounting JSON Server on another endpoint example

Alternatively, you can also mount the router on /api.

server.use['/api', router]

API

jsonServer.create[]

Returns an Express server.

jsonServer.defaults[[options]]

Returns middlewares used by JSON Server.

jsonServer.router[[path|object]]

Returns JSON Server router.

Deployment

You can deploy JSON Server. For example, JSONPlaceholder is an online fake API powered by JSON Server and running on Heroku.

Links

Video

Articles

Third-party tools

License

MIT

Supporters

Video liên quan

Chủ Đề