Custom routes, not able to PUT data, requires using the original routes
Adding in a custom route breaks the behavior.
Custom route:
"/api/rule_templates/:name": "/ruleTemplates?name=:name&singular=1&noerror=1",
This uses the name as a lookup, returns a single object instead of an array of objects, and does not throw a 404, instead gives a 200 with an empty object if nothing is found.
Problem: This breaks PUT, POST, DELETE, and PATCH operations. They will never hit the route /ruleTemplates/:name, they will always hit /ruleTemplates?name.
Proposed solution: It would take some time to implement, but add a two level json structure:
{
"/api/rule_templates/:name": {
"GET": "/ruleTemplates?name=:name&singular=1&noerror=1",
"POST": "/ruleTemplates/:name",
"PUT": "/ruleTemplates/:name",
"PATCH": "/ruleTemplates/:name"
}
}
This would close out several of the issues.
See #801, #793, , #791, #755, etc., etc., etc.
Hi, Where should put these route rules? Did this work when using "GET" "POST" ets as key?
··· { "/api/rule_templates/:name": { "GET": "/ruleTemplates?name=:name&singular=1&noerror=1", "POST": "/ruleTemplates/:name", "PUT": "/ruleTemplates/:name", "PATCH": "/ruleTemplates/:name" } } ···
I have figure that out. Using middleware to redirect these methods worked.
Working example to get around this frustrating bug, feel free to modify as needed:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('data.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
// Override the verb that doesn't work.
server.put('*', (req, res) => {
// Tweak if you actually need to modify your data, e.g. redirect to a different route.
res.send('');
});
// Use default router for everything else.
server.use(router);
const port = process.env.PORT;
server.listen(port, () => {
console.log(`JSON Server is running on port ${port} ...`);
});
To run: PORT=3000 node stub-server.js
@cooperka Hi thanks for the solution. But i need some more info regarding this.
I am doing a PUT / PATCH operation without giving the id in req URL, i am getting 404. If i specify an id in req url it is working fine. The idea is to fetch the id from req body and assign it to url then send a req to the server. I am unable to achieve this in both the ways ( module way and using cli ), is there any other working solution to achieve this goal?
@typicode is it possible to achieve this solution? Thanks in advance
i also need this, any update?