typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
72.54k stars 7k forks source link

Rewrite URL middleware doesn't work #579

Open maxkoretskyi opened 7 years ago

maxkoretskyi commented 7 years ago

I've added the following simple middleware:

module.exports = (req, res, next) => {
    console.log('runs');
    req.url = '/';
    next();
};

and run it like this:

json-server db.json --static . --middlewares ./rewrite.js

the code runs successfully as can be seen by logging runs and server log

  Loading db.json
  Loading ./rewrite.js
  Done

but the requests are not redirected to the root. Why?

typicode commented 7 years ago

I don't really know why it's not working, but if your purpose is to do simple rewriting you can use this instead: https://github.com/typicode/json-server#add-custom-routes

maxkoretskyi commented 7 years ago

Thanks

It doesn't work because json-server adds the custom middleware to the bottom of middleware stack, so when custom middleware gets executed everything else has finished processing. I think it should add it to the top of middleware stack.

Also, I tried the solution with routes but it didn't work. I've added the following to the routes.json file:

{
  "*": "/"
}

and ran the server like this:

json-server db.json --static . --routes routes.json

my routes were successfully loaded as reported by the log

Other routes

  • -> /

but I still get 404 for custom routes. Can you help?

typicode commented 7 years ago

The way custom routes should be defined has been updated in v0.11. Have you tried with the new syntax? https://github.com/typicode/json-server#add-custom-routes

What's the custom route you're trying to define?

maxkoretskyi commented 7 years ago

But this is what I already do. I wrote about that in the previous post:

{
  "*": "/"
}

and

json-server db.json --static . --routes routes.json

typicode commented 7 years ago

Sorry, I wasn't clear, I'm wondering why you want to redirect everything to / actually?

maxkoretskyi commented 7 years ago

No problem, I'm using a router with Angular and want for every request that doesn't find local resource to return index.html. In this way the framework will pick up the current route and initialize the app. This is not production of course. It'd be pretty easy to do with middleware, but routes will do as well.