Defining routes

By default, the json-server tool defines the following routes: https://github.com/typicode/json-server#routes.

We can also define our own routes, by creating a routes.json file, where we can rewrite existing routes to other routes: https://github.com/typicode/json-server#add-custom-routes.

For our blog app, we are going to define a single custom route: /login/:username/:password. We are going to link this to a /users?username=:username&password=:password query, in order to find a user with the given username and password combination.

We are now going to define the custom login route for our app:

  1. Create a new server/routes.json file with the following contents:
{
"/login/:username/:password": "/users?username=:username&password=:password"
}
  1. Then, adjust the start:server script in the package.json file, and add the --routes option, as follows:
        "start:server": "npx json-server --watch server/db.json --port 4000 --routes server/routes.json",

Now, our server will be serving our custom login route, which we are going to use later on in this chapter! We can try logging in by opening the following URL in our browser: http://localhost:3000/api/login/Daniel%20Bugl/supersecure42. This returns a user object; therefore, the login was successful!

We can see the user object being returned as text in our browser:

Accessing our custom route directly in the browser

As we can see, accessing our custom route works! We can now use it to log in users.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.171.121