I have an employees
endpoint with some data in my db.json
. I'm using node v6.14.9.
My server.js
looks like this:
// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.rewriter({
'/api/*': '/$1'
}))
server.use(router)
server.listen(3000, () => {
console.log('JSON Server is running')
})
Server starts on port 3000. If I open http://localhost:3000/employees, it works fine. However, opening http://localhost:3000/api/employees throws error 404 not found. Any suggestion what I'm doing wrong?
Just in case anyone stumbles here like I did, there's two ways to start json-server. And depending on how you start json-server will dictate where you put your rewrites:
Method one (official docs) is defining your rewrites in a routes.json
file.
Your routes.json
will look like this:
routes.json
{
'/api/*': '/$1'
}
and then you can start json-server using the command, assuming both db.json
and routes.json
are in the same folder:
json-server db.json --routes routes.json
Method two (official docs) is creating a server.js
file like the one in your example and you pass a json object with your rewrites to server.use(jsonServer.rewriter())
:
server.use(jsonServer.rewriter(
//json object with rewrites
));
Remember, in server.js
file, your rewrites must come before server.use(router)
. So like in your example, your rewrites will indeed look like this:
server.use(jsonServer.rewriter({
'/api/*': '/$1'
}));
server.use(router);
And then the server will be started with this line in server.js
:
server.listen(3000, () => {
console.log('JSON Server is running')
});
So to start json-server with server.js
you just use node:
node server.js
So the thing to note is that when you use Method 1, json-server doesn't know anything about your rewrites in server.js
.
And likewise when you use Method 2, json-server will not know anything about your rewrites in routes.json
.
So you have to pick whichever suits your needs best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With