json-server
json-server copied to clipboard
How do i create a new table using json-server
I am creating a new table eg "table_123" I wont to add a new entry in the json like this table_123 : []
So that I can use the url http://localhost:3000/table_123
Currently when I am trying to do a post with this url it gives 404 not found error. Which supposed will create a new entry in the json with the key as table_123.
How do i achieve this ???
Hi @kpatel1989,
I guess you want to add it dynamically using a URL and not by editing db.json.
For this, you need to use the project as a module and add a custom route https://github.com/typicode/json-server#custom-routes-example
For example, this should do the trick:
// server.js
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()
server.use(middlewares)
server.post('/:name', function (req, res) {
var ob = {}
obj[req.params.name] = []
// by default create an empty table named `name`
router.db.defaults(obj).value()
res.sendStatus(201)
})
server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
You just have to make a POST like POST /table_123.
router.db is an instance of lowdb in case you want to go further.
Hi @kpatel1989,
I guess you want to add it dynamically using a URL and not by editing
db.json.For this, you need to use the project as a module and add a custom route https://github.com/typicode/json-server#custom-routes-example
For example, this should do the trick:
// server.js var jsonServer = require('json-server') var server = jsonServer.create() var router = jsonServer.router('db.json') var middlewares = jsonServer.defaults() server.use(middlewares) server.post('/:name', function (req, res) { var ob = {} obj[req.params.name] = [] // by default create an empty table named `name` router.db.defaults(obj).value() res.sendStatus(201) }) server.use(router) server.listen(3000, function () { console.log('JSON Server is running') })You just have to make a
POSTlikePOST /table_123.
router.dbis an instance of lowdb in case you want to go further.
Typo near var ob = {}
need to add var obj = {}