简体   繁体   中英

Getting 404 while using json-server

I am learning to use json-server npm package.
I am using latest json-server version 0.17.0.
I want to get this data from url "http://localhost:3001/getFolderByFolder/14".Where 14 should match with folder_id.

{
  "folder_id": 14,
  "abstracts": {
    "33": {
      "abstract_name": "abstractt1",
    },
    "34": {
      "abstract_name": "abstract2",
    },
    "35": {
      "abstract_name": "abstract3",
    }
  },
  "folder_name": "folder2",
  "number_of_items": 2,
  "user_id": 6
}

I created db.json.I wrote this inside.

{
  "folders": {
    "folder_id": 14,
    "abstracts": {
      "33": {
        "abstract_name": "abstractt1",
        },
      "34": {
        "abstract_name": "abstract2",
      },
      "35": {
        "abstract_name": "abstract3",
      }
    },
    "folder_name": "folder2",
    "number_of_items": 2,
    "user_id": 6
  }
}

I created route.json in same folder.I wrote this inside.

{
  "routes": {
    "/getFolderByFolderId/:id": "/folders?folder_id=:id"
  }
}

I typed this command json-server --watch db.json --routes route.json --port 3001 在此处输入图像描述
I get 200 when http://localhost:3001/folders?folder_id=14.
Then why i am getting 404 on http://localhost/getFolderByFolderId/14.

I tried to change db.json as

{
  "folders": [{
    "folder_id": 14,
    "abstracts": {
      "33": {
        "abstract_name": "abstractt1",
        },
      "34": {
        "abstract_name": "abstract2",
      },
      "35": {
        "abstract_name": "abstract3",
      }
    },
    "folder_name": "folder2",
    "number_of_items": 2,
    "user_id": 6
  }]
}

Still getting 404.

I dont believe you need the routes: {} object in routes.json. Just simply your custom route inside an empty object like so:

   {
     "/getFolderByFolderId/:id": "/folders?folder_id=:id"
   }

Reference: https://shekhargulati.com/2019/07/10/how-to-setup-json-server-to-use-custom-id-and-route/

Also I just noticed when you mentioned having trouble with your route that you didnt mention utilizing a port number:

Blockquote I get 200 when http://localhost:3001/folders?folder_id=14. Then why i am getting 404 on http://localhost/getFolderByFolderId/14

Of course make sure that is formatted properly as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM