Appcelerator Blog

The Leading Resource for All Things Mobile

Building a custom front-end to ACS using Node.ACS [Part 1]

0 Flares 0 Flares ×

With Titanium you use Javascript to build native mobile Apps. With Node.ACS you now can use Javascript to write your back-end code, with super easy access to ACS database and storage, all hosted on our secure and scalable cloud infrastructure. As an added advantage, your local Node.ACS installation is a self-contained environment, that doesn’t require you to install a local web server for testing. As you will see later on, when you run a Node.ACS app, it is automatically listening for requests on a given HTTP Port; you just have to point your browser to it!

Getting started

Assuming you have Node and NPM, open up a terminal/command window and type:

$ sudo npm install -g acs

This will install Node.ACS globally on your computer. To start using it you need to login to your appcelerator account by typing:

$ acs login

Now that you have successfully logged in, you’re ready to create your first app. Change to the folder where you’d like your app to live, for example cd ~/Documents/MyApps and type:

$ acs new MyFirstApp

This command will create for you a new folder with the name of your new app. Now change to that folder (cd MyFirstApp) and you’ll see the files that were created for you. I’ll explain them later.

To run the app, simply type:

$ acs run

Your terminal/command window will show something like this:

When you run your app, Node.ACS is actually setting up a local server for you and at this point it is waiting for connections. As you can see in the screenshot above, ACS is listening on port 8080. This means that all you need to do is browse to that address. Launch up your web browser and point it to http://localhost:8080 and you’ll see this:

This HTML page is being served by your local Node.ACS server, but it’s much more than this. Node.ACS has a full-featured MVC framework based on ExpressJS. If you go to your application folder you’ll see that some files and folders were created for you.

These folders/files are explained in more detail in this page, so make sure you check it out. However, I’ll explain how to work with some of these files from a practical standpoint, and in the process we’ll create a complete website.

Building a Website

If you’re new to MVC this will probably take some time reading the code, testing and re-reading, but simply because of how MVC separates concerns. With an MVC framework, your pages(views) are static. When you want to make them dynamic, you pass static information to them. A templating engine then takes over to render the static page with new dynamic data. If you come from a background of developing websites using a “traditional” paradigm, MVC may feel weird at first. If you have worked with other MVC frameworks before, they you will feel right at home. In any case, MVC is arguably the best way of writing scalable applications.

If you go to your “Views” folder, you’ll see a file named “index.ejs”. Instead of an HTML extension, it is using EJS. The reason for this is that Node.ACS is using Embedded Javascript as its templating engine.

<!DOCTYPE html>
<html>
  <head>
     <title><%= title %></title>
    <link rel='stylesheet' href='/css/style.css' />
  </head>
  <body>
       <h2>Node.ACS</h2>
    <p><%= title %></p>
  </body>
</html>

Notice < %= title %> inside the Title Tag and the Body. This is the way you tell EJS to insert dynamic data into your template. Title in this case is a variable that was sent to the template before getting it rendered and sent to the browser. The benefit of using these templates is that you build your HTML as a static page, and use placeholders during your design process to represent dynamic data. When your page is ready to be implemented, you simply change the dynamic parts to use the corresponding variable name and save the file with .ejs extension. To show the page with dynamic data, you use the page controller, which you can find under controllers/application.js.

function index(req, res) {
     res.render('index', { title: 'Welcome to Node.ACS!' });
}

This function is receiving two objects: req and res. As their names imply, req has information about how the user got here (the request), and res holds information and provides methods to take the user some place else (the response).

In this example we’re using the “render” method of the res object. This method is receiving the name of the view, and an object with all the variables that you’d like to make available to your view, in this case title, and the static template gets rendered with this new data. If you change the value of title, you’ll see it changing on the browser. However your server is still running with a previous version of your files. You need to stop the server and restart it because that part of the Javascript function is already running and changes will not take effect until you run it again. This is as simple as going to your terminal, hitting CTRL+C to break the execution, and running “acs run” again; or simply pressing the “up” key on your keyboard which will type it for you.

We’re still missing one important detail. How do we tell the framework that the “main” page of your app will be handled by the index function that lives inside application.js? You configure these mapping (or route as they’re called) in config.json.

{
  "routes":
  [
    { "path": "/", "callback": "application#index" }
  ],
  "filters":
  [
        { "path": "/", "callback": "" }
  ],
  "websockets":
  [
       { "event": "", "callback": ""}
  ]
}

In this file we’re saying that when you browse to the home page, it will execute the function index inside application.js. We’ll see more about filters in the second part of this post, and websockets are explained here.

For simplicity, let’s create a trivial page that will be displayed when navigating to /newpage.

Step 1: Create your route by adding it to your config.json

[
    { "path": "/", "callback": "application#index" },
    { "path": "/newpage", "callback": "newpage#newpage" }
]

Step 2: Write the “newpage” function in newpage.js. I’m using a separate file for illustration purposes.

function newpage(req,res){
     res.render('newpage', { greeting: 'I am the new page' });
}

Step 3: Create the template called newpage and make sure it is using the new variable “greeting”.

<!DOCTYPE html>
<html>
  <head>
     <title><%= greeting %></title>
    <link rel='stylesheet' href='/css/style.css' />
  </head>
  <body>
       <h2>Node.ACS</h2>
    <p><%= greeting %></p>
  </body>
</html>

Restart your server and browse to your page. Then change the URL to http://localhost:8080/newpage and you’ll see the new page.

These are the basic principles for building websites using Node.ACS. To learn more about the EJS templating engine and how you can use loops, arrays and other fun Javascript features, go to http://embeddedjs.com/getting_started.html. To learn more about the “response” and “request” objects, you can go to http://expressjs.com/api.html#req.params.

If you want to publish your website for everyone to see, simply type

$ acs publish

Node.ACS will give you a public URL in return. The next time you publish, use the --force parameter to tell Node.ACS to overwrite your previous pages.

Final thoughts

This is a full-featured web MVC framework. You can use anything you’d normally use when developing websites, such as JQuery or Bootstrap. Just make sure that any library you use, or any dependency for that matter, is saved in the /public folder. From your views, the /public folder is the root folder, so if you placed an image at /public/image.png, from your view you would reference it like <img src=”/image.png” />

Stay tuned for the second part of this post, where we’ll apply this concepts to build a custom front-end to ACS.

Have fun!

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×

12 Comments

  1. LM

    Thanks for the great tutorial. You couldn’t have explained it easier!

  2. IW

    Thanks for the tutorial.
    Is it mandatory to use this architecture or directory structure.
    I have Node+Express+Jade+Mongo (mongoose) project that uses different structure. Can I deploy it into node.ACS, with only minor changes, or changes in package.json. Also, is the way to use the routes as described in this tutorial is mandatory or is it just a recommended best practice.

    • Ricardo Alcocer

      Hello IW.

      This tutorial is a basic guide of using Node.ACS’ built-in MVC framework. However, you’re free to use your own setup, so nothing is mandatory.

      R

  3. Sarat

    Hi Ricardo,
    I had posted a comment here http://developer.appcelerator.com/blog/2013/05/appcelerator-node-acs-financial-stock-watch-list.html/comment-page-1#comment-165792. My question about connecting to MongoDB is still not answered. A link to this article has been posted as a response. Am I to assume that there is a part 2 for this article that will address this?

    Thanks
    Sarat

  4. Sarat

    Hi Ricardo,
    Thanks for the response. I have explained in my previous comment (link above) that the sample is incomplete – what parameters do I provide for the db connection? I had asked for a working example.

    • Ricardo Alcocer

      Hi Sarat. I see what you mean. Give me a couple days to test it out and will report back.

      • Ricardo Alcocer

        Sarat, I went quickly through the connection code, and keep in mind that this code is for connecting to MongoDB, not to host a MongoDB server. I went ahead and created a quick MongoDB instance over at MongoLab.com, and it gave me the server and port parameters. Then I created a new DB and used those details for my Node.ACS connection. Here’s a Gist with the connection code: https://gist.github.com/ricardoalcocer/5723782.

        Hope this helps.

  5. Sarat

    Hi Ricardo,
    Thanks a bunch for the quick response. Much appreciated.

    Sarat

  6. Sarat

    Hi Ricardo,
    A quick question. I would like to avoid external service providers (mongolab.com) because Im not sure how reliable / scalable they are. Does Appcelerator support any db for the nodsJS platform?

    Thanks
    Sarat

  7. Imanol

    This is awesome, great tutorial, thanks a lot!

  8. Gerardo Camacho

    Hello Ricardo,

    Following on Sarat’s issue, I permitted myself to post a similar question in here:

    http://developer.appcelerator.com/question/156357/mongodb-connection-not-working-on-nodeacs-mvc

    I would really appreciate if you could check it out.

    Thanks a lot!

Comments are closed.

Sign up for updates!

Become a mobile leader. Take the first step to scale mobile innovation throughout your enterprise.
Get in touch
computer and tablet showing Appcelerator software
Start free, grow from there.
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×