Managing layouts

As mentioned in Chapter 2 , Model-View-Whatever, a layout in relation to an SPA is the server-side HTML page that is used to house, initialize, and display your app. The layout will contain similar HTML markup to the examples in the previous section regarding how to load your SPA container.

The layout is generally the only native server-side component necessary to create an SPA, the other components being the native frontend code and the external API for providing endpoints for data consumption and manipulation.

Static layouts

A layout can be something as simple as a static HTML page that is loaded onto a web server and calls the resources necessary for loading your app within a defined container element on that page. Ideally, once that initial HTML page is loaded, no other server-side HTML pages need to be accessed to run your app, hence the term Single Page Application.

If you do not require any server-side framework interaction for setting up environment variables, testing login state, and so on, then a static HTML page is the quickest and easiest way to launch your SPA.

A static HTML layout page could be something as simple as the following example:

<!doctype html> 
<html> 
    <head> 
        <title>This is a static HTML page</title> 
    </head> 
    <body> 
       <div class="container"> 
            The application will be loaded here. 
        </div> 
        <script src="app.js"></script> 
    </body> 
</html> 

A drawback to using a static HTML file simply being served on a web server is that you have to go directly to that file in order to load your app. If your app is reached at myapp.com, for instance, and your static HTML layout page is named index.html, most web servers will route the root server request to this page automatically, so a user would not need to navigate directly to myapp.com/index.html in order to reach it, but just to myapp.com.

If a user were to go to myapp.com/profile, however, where they might find their user profile information, the app layout would not be loaded and the server would generate a HTTP 404, or Not Found, response. In order to provide for this use case and allow custom URLs for your app, a dynamic layout is necessary.

Dynamic layouts

When you have control over the server-side framework for your single page application, as would be the case when using the MEAN stack, then you may want to develop a more dynamic server layout page that can load variables and some minimal logic from the server side when your app initially loads.

Express is a server-side web framework for Node.js, and it is the E in the MEAN stack acronym. When you are developing with the MEAN stack, you will be using Express to define and handle all of your REST API endpoints, but you will also want to handle your main application entry point.

Installing Express

Let's go back to our Node.js environment we have been using to work with NPM, Bower, and Grunt, and install Express:

$ npm install express --save

In this case, we are using the --save parameter to save Express to our main NPM dependencies, since it is not just being used for development.

Setting up a basic server with Express

Once you have Express installed, create a file called server.js in the root directory of your app:

$ touch server.js

Within this file, add the following code to include the Express module and initialize your application object:

var express = require('express'); 
var app = express(); 

The app object within your server.js file will allow you to call methods on it for defining routes. In the case of our SPA example, we only need to define one route for the time being.

Basic routing with Express

Routing in Express refers to defining URL paths which are used to respond to server requests. Express can define routes for any type of HTTP request, including GET, POST, PUT, and DELETE requests, which are necessary for creating a REST API. At this point, however, we simply want to define a route for loading a HTML page.

Defining a route for your main application entry point would be a GET request, and this is quite simple to do with Express. In the server.js file you just created, add the following code below the app object definition:

app.get('/', function(request, response) { 
    response.sendFile('/index.html', {root: __dirname}); 
}); 

This command adds a route that will serve the index.html file you created earlier as the root response for the app. The second parameter, which defines a root property as __dirname, simply sets the root server path for the app to the current directory.

Now we want to use Express to serve our app instead of the simple http-server module from earlier.

Running a server with Express

Now that you have your server.js file set up with a basic route to the root of your application, all that is left is to set up a HTTP port to listen on and to load the app. In your server.js file, add the following code to your route definition:

app.listen(8080, function() { 
    console.log('App now listening on port 8080'); 
}); 

This tells the server to listen on HTTP port 8080 for serving the app layout. Now all you have to do is run the server from the command line:

$ node server.js

This will run the server and display the console message App now listening on port 8080 in the terminal.

Now go to localhost:8080 in your browser and you should see the simple SPA page we created in Chapter 2, Model-View-Whatever. You will notice some errors in your browser console, however, because the local JavaScript files which are linked to in index.html are not found. This is occurring because you have not defined a route for loading static asset files.

Loading static assets with Express

First, stop the app by pressing Ctrl + C from the command line. Now edit server.js again and add the following code above the SPA layout page route definition:

app.use('/', express.static('./')); 

This command will set the app to load static assets from the root directory. Now if you run nodeserver.js again from the command line and reload the page in your browser, the SPA should load all assets and work just as it did before with http-server.

Dynamic routing with Express

As mentioned earlier, our app should allow a user to go to something like myapp.com/profile, or in our case localhost:8080/profile, to load a dynamic request that will trigger a different view than the main root view for the app. If you go to localhost:8080/profile in your app now, you will get the following response in your browser:

Cannot GET /profile 

To fix this, stop your local server again, edit the server.js file and make the following change to the app layout route definition:

app.get('*', function(request, response) { 
    response.sendFile('/index.html', {root: __dirname}); 
}); 

Here, we simply changed the path parameter in the GET route definition from '/' to '*'. Express allows for regular expression syntax within route definitions, so what this does is tell the server to route all dynamic path requests to the index.html page, instead of just the root '/' path.

Save this change, and now if you run node server.js again on the command line and go to localhost:8080/profile in your browser, you will see the SPA displayed again just as it did from the root path, and all static asset files should be loaded as expected.

After setting up this basic Node.js Express server, your final server.js file should look like this:

var express = require('express'); 
var app = express(); 
 
app.use('/', express.static('./')); 
 
app.get('*', function(request, response) { 
    response.sendFile('/index.html', {root: __dirname}); 
}); 
 
app.listen(8080, function() { 
    console.log('App now listening on port 8080'); 
}); 

Our simple SPA has now become a bit more sophisticated, with the ability to serve a dynamic layout file, and to use dynamic routes for loading the layout via custom URLs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.247