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

Issue with having to add a /data to my query for json-server to find the data.

Open Leviathan91 opened this issue 3 years ago • 1 comments

I am having trouble even describing my problem properly, so I lead by giving an example. Right now I have to modifiy my real data when using it as mock data for the json-server (and the tests which I use it for) to work.

My original json looks like something like this:

[
  { "searchTerm" : bla, stuff, more stuff.. },{ "searchTerm" : bla, other stuff, more stuff.. }
]

to make it work, I had to change the mock to this:

{
  "data" : [
      {  "searchTerm" : bla, stuff, more stuff.. },{ "searchTerm" : bla, other stuff, more stuff.. }
    ]
}

and the url I use for the mock server is http://localhost:3030/data?searchTerm=

I would like to omit the /data part - but I do not know how. I tried adding a routes.json with

{
  "/data/*": "/$1"
}

but this did not work. This is very confusing, because when I do not use the json-server to fetch the data, now I have to do something like this in my tests const mockJSON = JSON.parse(mockData).data;. This will surely be problematic for someone else who reads the codebase. Also I am sure that my original workaround is uncessary, I just couldn't figure it out on my own. So help is appreciated!

Leviathan91 avatar Apr 22 '22 07:04 Leviathan91

I don't understand what you are trying to achieve. But given the example in your db.json the data route is already provided. By adding that custom route "/data/*": "/$1" you are saying that any incoming route with /data will be rewritten to /. So /data/foo will be rewritten to /foo. This custom route is useful when you have a route you need to match from your production server that should be similar to the mock. So like the example in the doc is provided a /api. But json-server is already providing you the /data route since it's defined in the db.json

bu3alwa avatar Apr 22 '22 19:04 bu3alwa