json-server icon indicating copy to clipboard operation
json-server copied to clipboard

Custom routes, not able to PUT data, requires using the original routes

Open NoMan2000 opened this issue 8 years ago • 5 comments

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.

NoMan2000 avatar Jun 15 '18 00:06 NoMan2000

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" } } ···

imageslr avatar Apr 10 '19 09:04 imageslr

I have figure that out. Using middleware to redirect these methods worked.

imageslr avatar Apr 12 '19 03:04 imageslr

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 avatar Nov 13 '19 00:11 cooperka

@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

riyazmulla51 avatar Apr 28 '20 12:04 riyazmulla51

i also need this, any update?

ToledoNicola avatar Sep 02 '21 17:09 ToledoNicola