I have fake api for testing in frontend side.
i have seen that id is required to put or post your data in json-server package, my question is can i use different key instead of id for ex.
{
id: 1, ---> i want to change this with my custom id
name: 'Test'
}
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. So you can't send a PUT without the ID.
json , you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults. js in your project, then add the port in "modules. export" like this.
Starting as node module If you start your json-server as a node module instead, you can add custom routing by using the rewrite middleware that comes bundled with json-server.
Let's see CLI options of json-server package:
$ json-server -h
...
--id, -i Set database id property (e.g. _id) [default: "id"]
...
Let's try to start json-server with new id called 'customId' (for example):
json-server --id customId testDb.json
Structure of testDb.json file: $ cat testDb.json
{
"messages": [
{
"customId": 1,
"description": "somedescription",
"body": "sometext"
}
]
}
Make a simple POST request via $.ajax
function (or via Fiddler/Postman/etc.). Content-type
of request should be set to application/json
- explanation may be found on this project's github page:
A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will result in a 200 OK but without changes being made to the data.
So... Make a request from Browser:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:3000/messages/',
data: {body: 'body', description: 'description'},
success: resp => console.log(resp),
dataType: 'json'
});
Go to testDb
and see the results. New chunk added. id automatically added with the desired name specified in --id key
of console cmd.
{
"body": "body",
"description": "description",
"customId": 12
}
Voila!
I've came up with using custom routes in cases where I need custom id: json-server --watch db.json --routes routes.json
routes.json:
{ "/customIDroute/:cusomID" : "/customIDroute?cusomID=:cusomID" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With