Let’s raise the anchor and learn to steer our new vessel.
Part 2: Navigating the Harbor (Routes & Controllers)
- Current Rank: Seaman
- Objective: To build and install the ship’s rudder and steering mechanism, allowing you to control how your application responds to specific requests from the outside world.
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'
GET
: This is the HTTP Verb or method.GET
is used for retrieving data, like when you type a URL into a browser address bar. We’ll encounter others likePOST
(for creating data) later./path/to/some/url
: This is the URL path that triggers the route.'ControllerName.actionName'
: This is the destination, the specific “dock” where the request will be handled.
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:
req
(Request): An object containing all information about the incoming request. It’s the message in a bottle from the user, telling you what URL they visited, what data they sent, and who they are.res
(Response): An object containing a set of methods for you to send a response back to the user. It’s your toolkit for sending a message back. You can send back raw data (res.json()
), a full web page (res.view()
), or just a simple confirmation (res.ok()
).
Today, we will generate our first Controller and create an action that sends a simple JSON response back to the user.
Key Concepts Checklist
Route
: A rule inconfig/routes.js
that maps a URL to a controller action.Controller
: A file (api/controllers/YourController.js
) that groups related actions.Action
: A function inside a controller that handles a single request.req
(Request Object): Contains information about the incoming request.res
(Response Object): Used to send a response back to the user.res.json()
: A response method that sends data formatted as JSON.sails generate controller
: The CLI command to create a new, empty controller file.
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.
Task 1: Recruit a Harbor Master (Generate a Controller)
- Make sure your terminal is still inside your
the-sea-serpent
project directory. Use the Sails “generate” command to create a controller for your Captain.
sails generate controller CaptainController
- Sails will confirm it has created the file
api/controllers/CaptainController.js
.
- Make sure your terminal is still inside your
Task 2: Define Your Orders (Create the Action)
- Open the new
api/controllers/CaptainController.js
file in your code editor. It will be mostly empty. Add the
greet
action to it. Replace the contents of the file with the following code:module.exports = { greet: function(req, res) { // This action sends a JSON response. // JSON is a standard format for sending data on the web. return res.json({ message: 'Ahoy there, Captain!' }); } };
- Open the new
Task 3: Chart the Shipping Lane (Create the Route)
- Now, open the harbor map:
config/routes.js
. Inside the
module.exports.routes
object, add a new line to define our route. The best place is just above the'/': { view: 'pages/homepage' }
line.module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` your home page. * * * * (Alternatively, remove this route and create an `index.html` file in * * the `assets` directory) * * * ***************************************************************************/ 'GET /hail': 'CaptainController.greet', // <-- ADD THIS LINE '/': { view: 'pages/homepage' }, /*************************************************************************** * * * More custom routes here... * * (See https://sailsjs.com/config/routes for examples.) * * * * If a request to a URL doesn't match any of the routes in this file, it * * is matched against "shadow routes" (e.g. blueprint routes). If it does * * not match any of those, it is matched against static assets. * * * ***************************************************************************/ };
- Now, open the harbor map:
Task 4: Test Your New Route
- If your server is already running, stop it (
CTRL
+C
) and restart it withsails lift
to make sure it recognizes your new controller and route changes. - Open your web browser and navigate to
http://localhost:1337/hail
. - Instead of a web page, you should see the raw JSON text you defined in your action:
{"message":"Ahoy there, Captain!"}
- If your server is already running, stop it (
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
- +150 Doubloons
- Achievement Unlocked: You’ve created your first working route and controller action. You are no longer just floating; you are navigating!
- Badge Earned:
First Heading
ðŸ§
- Badge Earned:
- Promotion to: Boatswain
Excellent work, Boatswain. You have authority on deck. Now, it’s time to make our ship presentable to visitors.