What Is A Route In Express: Simplest Explanation

What Is A Route In Express: Simplest Explanation

·

2 min read

If Express.js is the first backend framework you have ever learned, route is the next topic I recommend learning after mastering MVC.

What Is A Route?

Basically, a route is the "address of a particular page". A route (or specifically the route address) is what I would add to the web address to display a page.

This syntax for creating routes is as follows:

router.get('/routename', function(){});

The first parameter is the name of your route, the second parameter is what you want to execute (as a function) at the route.

For example, if I want to use the age-old example of displaying "hello world" when I try the route of "hello", I would write:

Example

router.get("hello", function(req, res, next)
{
res.send("Hello World");
});

A Better More Proper Way

In reality, you should actually write what happens in the route as part of a controller's function other than directly, as I've done above.

router::get(‘/hello” ‘HelloController.hello’)

That line of code would go in the index.js file in the routes folder (which was created by default by Express.js).

And we include a controller file with a class name of HelloController as below:

class HelloController
{
function hello(req, res, next)
{
res.send("hello world");
}
}

The result is the same, but you generally use controllers to organize your content rather than writing them directly.

In Summary

To create a route, use the syntax router.get(/*route name*/, /*route address*/), where route address is usually a controller's function (you can of course use POST in place of GET).