Ahoy! Sails
Say Ahoy! Sails
Summary
In this lesson, we learn how to create a new page in Sails by defining a route, creating an action, and setting up a corresponding view.
Understanding the Default Page
The default homepage is rendered based on
homepage.ejs
inviews/pages/
, defined inconfig/routes.js
.
Creating a New Page
Add a new route in
config/routes.js
forGET /articles
, handled byarticle/index
action.If the action doesn’t exist, Sails returns a 404 error.
Generating the Action
Run
sails generate action article/index
to create theindex.js
action file underapi/controllers/article/
.
Modifying the Action
Define a
success
exit in the action to return a view fromviews/pages/articles/index.ejs
.
Creating the View
Create
views/pages/articles/index.ejs
and add simple content (<h1>Ahoy! Sails</h1>
).
Running the Server
Restart the Sails server with
sails lift
and visithttp://localhost:1337/articles
to see the new page.
Transcript
Alright, now in this lesson, we're going to look at how to create a page in Sails.
If we start up the Sails server and go to http://localhost:1337, we see the default homepage. So, how does this page get rendered?
Let's open Visual Studio Code and check config/routes.js
. This file is responsible for declaring routes in our application. Right now, it only has one entry for the homepage, which serves homepage.ejs
from views/pages/
.
Now, let's create a new page:
Define the Route
Add a new entry for
GET /articles
.Instead of directly mapping to a view, we define a controller and action to handle it.
We'll create a controller named Article and an action called index.
Generate the Action
Run
sails generate action article/index
.This creates
api/controllers/article/index.js
.Opening
index.js
, we see a boilerplate Sails action.
Modify the Action
The
fn
function runs when the route is requested.We define a
success
exit that renders a view.Set
viewTemplatePath: 'pages/articles/index'
(Sails auto-appends.ejs
).
Create the View
Inside
views/pages/
, create a new folderarticles/
.Add a new file
index.ejs
with<h1>Ahoy! Sails</h1>
.
Test the Page
Restart the server with
sails lift
.Visit http://localhost:1337/articles and see "Ahoy! Sails".
That’s how you create a new page in Sails by defining a route, adding an action, and setting up a view!
Full Course
USD