Search code examples
jsonhttpjson-server

json-server returns 404 for specific URI


I use json-server and my codes are like below.

db.json

{
  "en-boards": [
    {
      "id": 0,
      "name": "News",
      "uri": "/board/en-news"
    },
    {
      "id": 1,
      "name": "Politics",
      "uri": "/board/en-politics"
    }
  ],
  "board-en-news-threads-latest": [
    {
      "id": 0,
      "poster": null,
      "zero-post": "This is a thread 0.",
      "attachment-path": null,
      "post-number": 100,
      "utc-timestamp": "2022-01-01T00:00:00"
    },
    {
      "id": 1,
      "poster": null,
      "zero-post": "This is a thread 1.",
      "attachment-path": null,
      "post-number": 100,
      "utc-timestamp": "2022-01-01T00:00:00"
    }
  ]
}

routes.json

{
  "/api/*": "/$1",
  "/api/en-boards": "en-boards",
  "/api/board/en-news/threads/latest": "board-en-news-threads-latest"
}

I run json-server --watch db.json --routes routes.json --middlewares middleware.js --port 4000

When I run curl -i http://localhost:4000/api/en-boards, I get 200 OK, but when I run curl -i http://localhost:4000/en-news/threads/latest, I get 404 Not Found. wget and React app behave in the same way.

Environment

  • MacOS 13.0
  • Node.js 18.11.0
  • json-server 0.17.0
  • curl 7.84.0
  • wget 1.21.3
  • React 18.2.0

Thank you for read. Any help would be appreciated.


Solution

  • Have faced something similar before...
    In my case, I needed something like base URLs (1) and endpoint paths (2) like the below - enter image description here

    {
    "/api/board/*": "/$1",
    "/api/*": "/$1",
    "/en-boards": "/en-boards",
    "/en-news/threads/latest": "/board-en-news-threads-latest"}
    

    This would cater to the following endpoints being hit

    http://localhost:3000/api/board/en-news/threads/latest
    http://localhost:3000/api/en-news/threads/latest
    http://localhost:3000/en-news/threads/latest
    
    http://localhost:3000/api/board/en-boards
    http://localhost:3000/api/en-boards
    http://localhost:3000/en-boards
    

    Note: for /api/board/en-news/threads/latest to route to /board-en-news-threads-latest, the order for the base URLs needs to be maintained (i.e.)

    "/api/board/*": "/$1",
    "/api/*": "/$1",
    

    Hope this helps :)