Learn Sails.js - Part 2

von Manuel am 31.08.2025 um 12:00 Uhr

Let’s raise the anchor and learn to steer our new vessel.


Part 2: Navigating the Harbor (Routes & Controllers)


The Captain’s Briefing (Background and Theory)

Our sloop, the-sea-serpent, is afloat. It’s a magnificent sight, but currently, it just bobs aimlessly in the harbor. To go anywhere, we need to steer. This module is all about building that steering mechanism. In Sails.js, this is handled by Routes and Controllers.

Routes: The Official Shipping Lanes

Imagine the harbor your ship is in. A Route is an officially charted shipping lane. It’s a rule you define that says, “When a vessel hails us on this specific path (a URL), direct it to that specific dock (a piece of your code).”

These rules live in a single, critical file: config/routes.js. This file is your master map of the harbor.

A basic route definition looks like this: 'GET /path/to/some/url': 'ControllerName.actionName'

Controllers: The Harbor Masters

If a route is the shipping lane, a Controller is the Harbor Master. It’s a file in your api/controllers/ directory that contains the logic for handling requests. You can have many controllers, each one a specialist in handling a certain type of traffic.

Each function inside a controller is called an Action. An action is the specific code that runs when a route points to it. It’s the individual Harbor Master at the dock who personally greets the incoming ship.

Every action receives two crucial objects as arguments:

Today, we will generate our first Controller and create an action that sends a simple JSON response back to the user.


Key Concepts Checklist


Mission Log: Quest - “Establish a Port of Call”

In this quest, we will create a custom URL /hail. When a user visits it, our application will respond with a friendly JSON greeting.


Mission Debrief (Review & Outcomes)

Mission accomplished! Our ship now has a working rudder. You have successfully created a custom endpoint for your application.

Let’s trace the journey of that request: 1. Your browser sent a GET request to /hail. 2. The Sails router checked the config/routes.js file and found a matching rule. 3. That rule directed the request to the greet action inside the CaptainController. 4. Your action’s code executed, using res.json() to send a greeting back to the browser.

You are now in control. You can define any URL and make your application do anything you want in response. Right now, we’re just sending data, but soon we’ll use this same mechanism to display full pages, save data, and build complex features.


Rewards & Promotion

Excellent work, Boatswain. You have authority on deck. Now, it’s time to make our ship presentable to visitors.