The LocalLibrary website
- Name of the website that we’ll create and evolve over the course of these tutorials.
- Provide an online catalogue for a small local library.
- Start by creating a skeleton project.
Overview
- Create a skeleton website using Express Application Generator.
- Can then popular with site-specific routes, views/templates and database calls.
Using the application generator
- Need to make sure that we have already installed the generator:
npm install express-generator -g
- Number of options: express —help
- Specifc express to create a project inside the current directory, as well as the view engine and plain css.
- So, to create the project:
express express-locallibrary-tutorial --view=pug
- The generator will create (and list) the project’s files:
- Then we need to: cd express-locallibrary-tutorial
- Install: npm install
- Run the app: DEBUG=express-locallibrary-tutorial:* npm start
Running the skeleton website
- To run the website, we install the dependencies
- Need to change into our project directory
- And then install
cd express-locallibrary-tutorial
npm install
DEBUG=express-locallibrary-tutorial:* npm start
- Can then test: http://localhost:3000/
Enable server restart on file changes
- Any changes you make to your Express website – not currently visible until you restart the server.
- Irritating to have to stop and start the sever every time.
- Can actually automate restarting the server when needed.
- nodemon -> convenient tool for this purpose.
- Usually installed globally, but we will install it as a dev dependency
- Tool isn’t installed globally, can’t launch it from the command line.
- Can call it from an NPM script.
- Do this in package.json.
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www",
"serverstart": "DEBUG=express-locallibrary-tutorial:* npm run devstart"
},
- Can now start the project using npm run devstart
The Generated Project
- Directory Structure
- package.json
- has the cookie-parser file – this parses the cookie header and populates req.cookies.
- debug – tiny node debugging utility
- morgan – http request logger middleware for node
- http-errors – http errors where needed.
- www file
- application entry point
- All the does is require the real application entry point (app.js)
- Then returns the express application object
- app.js
- This file creates an express application object
- Next we create the app project using the imported express module
- Set up the view (template) engine.
- Se the new value to specify where the templates will be stored.
- Set the view engine to specify the template library (e.g. pug).
- Routes are stored in the routes/ directory.
- Templates in the /views directory
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug’);
- Next set of functions call app.use()
- This adds the middleware libraries into the request handling chain.
- Also use static, as well as json, urlencoded, cookieParser
- Then we use the routers – e..g app.use(‘/‘, indexRouter)
- See above. This ‘calls’ it.
- Last middleware: adds handler methods for errors and HTTP404 responses.
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
- Final step is to export it
module.exports = app;
Routes
- users.js and index.js have a similar structure, so we don’t need to show both.
- First, loads the express module, uses to get an express.Router object.
- Specifies a route on the object, exports the router from the module.
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
- Route defines a callback that will be invoked whenever a HTTP get request with the correct pattern is detected.
- Add the moment, this just sends back ‘respond with a resource’. We will fix that in time.
Views (templates)
- Stored in the /views directory (specified in app,js)
- Given the file extension .pug.
- Method Response.render() used to render a template along with the values of named variables passed in an object.
- Sends the result as a response.
- E.g.
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
- This passes a variable – title
- To show that in the template:
extends layout
block content
h1= title
p Welcome to #{title}