Routes

Routing refers to how an application’s endpoints (URIs) respond to client requests.

A route is a code that represents an HTTP action, (GET, POST, PUT, DELETE). It has a URL endpoint, a function that is used to handle when that endpoint is accessed.

We use postman to test these endpoints. Accessing these endpoints before setting up the code will return a 404 NOT FOUND - an HTML response.

Let's look at the code for a GET request at the greeting endpoint.
We call the get method on the app object, passing in two arguments

  • The Endpoint.

  • The function to handle this endpoint. It takes in a request and a response object as parameters.

app.get('/api/greeting', (req, res) => {
    res.send('Hello there, Welcome!')
} )

Now, if we access the route, we get a 200 OK status and the String "Hello there...." is returned.

Usually, we are gonna return JSON data. So the above code could be changed to

app.get('/api/greeting', (req, res) => {
    res.status(200).json({message:'Hello there, Welcome!'})
} )

We also set the status, although not necessary. Now we respond with a JSON object and the content type of the response changes from html to application/json. Even though we didn't add quotes on the key "message", it get parsed into JSON.

Now we don't wanna clutter our server.js file with all these routes. So we clean it up.

In the backend folder, we create a folder called 'routes' and in it we create file greetRoutes.js. So basically each resource in API will have it's own route file.

Folder structure: backend/routes/greetRoutes.js

Now to use the express router, we are gonna first bring the express into this file.

#greetRoutes.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    res.status(200).json({message:'Hello there, Welcome!'})
} )

module.exports = router

and inside server.js

#server.js
....
app.use('/api/greeting', require('./routes/greetRoutes.js');
...

So now, if we hit /api/greeting, it's gonna look into the Route file, and all we needed was a / because /api/greeting is already specified.

Similarly, we can create other routes for POST, PUT, and DELETE.
Some of them will require a ':id' in the endpoint part so that they access the right data point. router.put('/:id', (req,res) => {....})

Next up, Controllers. Again to clear the clutter!