Sails Tutorial — Chapter 2

Jun 19, 2024

This is the second article in the series. You can read the first one at this link.

Application is up and running at http://localhost:1337 but it throws a 404 error. Let’s fix it by adding a root route. To do so, first create a config folder and then routes.js file within config folder.

mkdir config
touch config/routes.js

Open the config/routes.js file and write the following code.

module.exports.routes = {};

It exports the routes object that will have all the routes of the application.

Go ahead define a root route or GET / as follows.

module.exports.routes = {
  'GET /': 'HomeController.index',
};

Meaning that when the root route (/) is requested, server run the index action (or method) from the HomeController. But, we don’t have controller and action.

Go ahead and create a folder with the name api. Within this api folder, create a folder with name controllers. In this folder, we’ll put all the application controllers.

mkdir api
mkdir api/controllers

Finally, within this controllers folder, create a file with the name HelloController.js. The name of the file should be the same as the controller name defined in routes.js file.

touch api/controllers/HomeController.js

Open the api/controllers/HomeController.js file and write the following code.

module.exports = {};

It exports the object that will have all the actions we are interested in calling from this controller.

Sails internally uses Express framework. So, the actions within the controller are essentially the callback function we usually write in Express for a given route with req and res (and next) parameters.

Let’s define an index as a named function that returns a sample JSON response.

module.exports = {
  index: (req, res) => {
    res.json({ message: 'Home page' });
  },
};

That’s it! Reload (or open) the http://localhost:1337 in the browser. You should now see a JSON response with the message { "message": "Home page" } instead of a 404 error page.

Take a break and read the second article in this series at this link.

Tags: sails