"/test/:start/:end": "/pagination?_start=:start&_end=:end"
this doesn't work
res
.
isAuthenticated(req)
method, I want to check if the request had a certain header (auth token). I keep doing console.log(req)
to see where I can find the headers I send.. but to no avail - I can not for the life in me find headers in the request.
req.headers
doesn’t show the token that I do send in my req, actually those headers are all different from the ones I send.
req.headers
is the object of the headers sent from the client
const isAuthorized = (req) => {
return req.headers['AUTH_TOKEN'] ? true : false;
}
I have a nice solution using --middleware ;)
package.json:"startAPI": "json-server --watch server/mockedBackendAPI.json --routes server/mockedBackendRoutes.json --port 3004 --middlewares server/middleware.js"
middleware.js:module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
@TW-OY
save this following code in a file called middlewares
module.exports = (req, res, next) => {
console.log('url', req.url);
console.log('path', req.path);
if (req.url == '/test') {
res.redirect('/');
}else{
next();
}
};
then run json-server as follow:
json-server db.json --middlewares middlewares.js
browse:
http://localhost:3000/test
or if you want more generic way of handling your static assets, you could use --static
option in the command line
create public/assets/index.html
file create directories if not exist
json-server db.json --static public
http://localhost:3000/assets
will serve public/static/index.html
.. and so on
I have models with optional relations to eachother and have a problem with DELETE
.
The data for a model foo
could look like this initially:
{
"foos": [
{
"id": 1,
"title": "A foo"
}
]
}
After adding a bar
and connecting it to my foo
it would look like this:
{
"foos": [
{
"id": 1
"title": "A foo",
"barId": 1
}
],
"bars": [
{
"id": 1
"title": "A bar"
}
]
}
Now I want to DELETE
the foo
with id 1
. But I don't want to delete the bar
. Speaking in terms of SQL I do not want an ON DELETE CASCADE
as it looks like it is doning now. In case I DELETE
the bar
instead I would like the barId
property in the foo
to either be set to undefined
(like with ON DELETE SET NULL
) or just removed from the foo
object.
Is this possible with json-server today?
@PerWiklander short answer. No.
Long answer:json-server
is an express server so you can do all kind of workarounds you wish.
You should first use json-server as module not CLI.
Giving that json-server db is in json-server router object
One workaround on my mind now is to write a simple middleware that intercept DELETE /foos/:fooID
then using lowdb's API, get thebar
by its id
, update the value, then save the db db.write()
Please find my anser here, might help too
please let me know if this is not clear so I can find sometime to create an example for you.