I need to do custom response for a couple of POST requests in order to fake/bypass an authentication process. As far as I know, I need to use json-server as a module rather than CLI program to do this.
My previous CLI implementation is along these lines
json-server --static ./www --watch db.js --routes routes.json
The README doesn't really cover how that would translate to usage in modules. I dig through the code and figured out jsonServer.defaults({static: './www'}) takes care of the static asset hosting, but I ran into problems with the actual data and routing.
jsonServer.router() only seems to support JSON file name, but I need to generate the data and use a JS module instead. Importing the db.js and passing it to the jsonServer.router() doesn't seem to load any of the data, despite working fine with the CLI version.
Also I can replace the --routes routes.json by passing similar data object to the jsonServer.rewriter(), but can't figure out how to use an external resource like the routes.json for it.
All help would be much appreciated. The README is a bit light on the module implementation.
Thank you for the feedback. I agree, it needs to be improved.
For the remaining parts, you can do it this way:
var generate = require('./db')
// generate should return an object
var router = jsonServer.router(generate())
// You can also do later
router.db.object = generate()
var routes = require('./routes.json')
server.use(jsonServer.rewriter(routes))
Let me know if it helps or there are missing things.
Exactly what I needed. Thank you.
Can you provide a full example for creating a express server using a JSON?
@warapitiya or anyone that reaches this issue now. This is a working example of importing routes.json + db.js files to your server.js file
const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const generate = require('./db')
const routes = require('./routes.json')
const router = jsonServer.router(generate())
server.use(middlewares)
server.post('/my/custom/response', (req, res) => {
res.json({
results: {
response: 'test'
}
})
})
server.use(jsonServer.rewriter(routes))
server.use(jsonServer.bodyParser)
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
What about setting the host with json-server running as a module? I set it this way using the CLI, --host mockapi.test.com.
This worked, same as John's solution: jsonServer.defaults({host: 'mockapi.test.com'})
Most helpful comment
Can you provide a full example for creating a express server using a JSON?