Locked video

Please purchase the course to watch this video.

Buy Now

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.

  1. Understanding the Default Page

    • The default homepage is rendered based on homepage.ejs in views/pages/, defined in config/routes.js.

  2. Creating a New Page

    • Add a new route in config/routes.js for GET /articles, handled by article/index action.

    • If the action doesn’t exist, Sails returns a 404 error.

  3. Generating the Action

    • Run sails generate action article/index to create the index.js action file under api/controllers/article/.

  4. Modifying the Action

    • Define a success exit in the action to return a view from views/pages/articles/index.ejs.

  5. Creating the View

    • Create views/pages/articles/index.ejs and add simple content (<h1>Ahoy! Sails</h1>).

  6. Running the Server

    • Restart the Sails server with sails lift and visit http://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:

  1. 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.

  2. 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.

  3. 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).

  4. Create the View

    • Inside views/pages/, create a new folder articles/.

    • Add a new file index.ejs with <h1>Ahoy! Sails</h1>.

  5. 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

$
29.99

USD

plus local taxes
Buy Now