Skip to content

Instantly share code, notes, and snippets.

@mrhammadasif
Created September 5, 2022 14:15
Show Gist options
  • Save mrhammadasif/006ee88d75d5fa7cd56e45f16308409b to your computer and use it in GitHub Desktop.
Save mrhammadasif/006ee88d75d5fa7cd56e45f16308409b to your computer and use it in GitHub Desktop.
Dynamic Routes in json-server with CORS enabled for API server
const dynamicMiddleware = require( 'express-dynamic-middleware' )
const jsonServer = require( "json-server" )
const jsonFile = "db.json"
const server = jsonServer.create()
let router = jsonServer.router( jsonFile )
let dynamicRouter = dynamicMiddleware.create( router )
const defaults = jsonServer.defaults()
server.use( '/:name', function ( req, res, next ) {
if ( req.method === 'POST' ) {
if ( !router.db.get( req.params.name ).value() ) {
router.db.defaults( { [req.params.name]: [] } ).write()
dynamicRouter.unuse( router )
router = jsonServer.router( jsonFile )
dynamicRouter = dynamicMiddleware.create( router )
server.use( dynamicRouter.handle() )
}
}
next()
} )
server.use( defaults )
server.use( dynamicRouter.handle() )
server.listen( 8899, () => {
console.log( 'API listening on port 8080.' )
} )
{
...
"dependencies": {
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express-dynamic-middleware": "^1.0.0",
"json-server": "^0.17.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment