3

I am trying to use json-server for my application. My json file goes like this:

{
  "Categories": [
    {

      "item": [
        {
          "id": 1,
          "product_id": 1,
          "description": "Pizza1",
          "price": 12.99,
          "pickup": 0
        },
        {
          "id": 2,
          "product_id": 2,
          "description": "Pizza2",
          "price": 8.99,
          "pickup": 1
        },
        {
          "id": 3,
          "product_id": 3,
          "description": "Pizza3",
          "price": 36.99,
          "pickup": 0
        }
      ]
    }

  ]
}

So the item is inside Categories. Now I am trying to add an item to to JSON file and I am not able to do that. I can successfully add a Category by doing: this._http.post('http://localhost:3000'+'/Categories',{JSON STRUCTURE}) but I cannot add things inside Category. It is not something like attaching /Categories/item at end of localhost:3000

The documentation's "custom routes" is really confusing me.

Wild Beard
  • 2,919
  • 1
  • 12
  • 24
Monkey
  • 55
  • 1
  • 6
  • What "documentation" are you referring to? Where is your insert code and endpoint for adding an item? – Wild Beard May 11 '18 at 16:05
  • https://www.npmjs.com/package/json-server#add-custom-routes – Monkey May 11 '18 at 16:21
  • [Filter](https://www.npmjs.com/package/json-server#filter) allows you to access nested properties. Try posting to `/Categories.item` instead of `/Categories/item` – Wild Beard May 11 '18 at 16:28

1 Answers1

2

This is not supported by the library. The way to get this working is to add a custom routes file to de server, where you will map (or redirect) requests made to /rest/user/ to /.

db.json

 {
    "item": [
        {
          "id": 1,
          "product_id": 1,
          "description": "Pizza1",
          "price": 12.99,
          "pickup": 0
        },
        {
          "id": 2,
          "product_id": 2,
          "description": "Pizza2",
          "price": 8.99,
          "pickup": 1
        },
        {
          "id": 3,
          "product_id": 3,
          "description": "Pizza3",
          "price": 36.99,
          "pickup": 0
        }
      ]
    }

routes.json

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

and then run it using json-server db.json --routes routes.json

Hope it helps!

Nicolas
  • 1,193
  • 1
  • 10
  • 25