Introduction
Aside from building APIs, Node.js is great for building standard web applications. It has powerful tools to meet the taste of web developers. In this tutorial, you will be building a web application that can serve as a local library.
While building you will learn about some types of middleware, you will see how to handle form submission in Node.js, and you will also be able to reference two models.
Let's get started.
Getting Started
Start by installing the express generator on your machine.
npm install express-generator -g
Run the express generator command to generate your application.
express tutsplus-library --view=pug
create : tutsplus-library create : tutsplus-library/package.json create : tutsplus-library/app.js create : tutsplus-library/public create : tutsplus-library/routes create : tutsplus-library/routes/index.js create : tutsplus-library/routes/users.js create : tutsplus-library/views create : tutsplus-library/views/index.pug create : tutsplus-library/views/layout.pug create : tutsplus-library/views/error.pug create : tutsplus-library/bin create : tutsplus-library/bin/www create : tutsplus-library/public/javascripts create : tutsplus-library/public/images create : tutsplus-library/public/stylesheets create : tutsplus-library/public/stylesheets/style.css install dependencies: $ cd tutsplus-library && npm install run the app: $ DEBUG=tutsplus-library:* npm start
Now migrate into your working, open package.json, and make the dependencies similar to what I have below.
#package.json { "name": "tutsplus-library", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.17.1", "connect-flash": "^0.1.1", "cookie-parser": "~1.4.3", "debug": "~2.6.3", "express": "~4.15.2", "express-messages": "^1.0.1", "express-session": "^1.15.5", "express-validator": "^4.2.1", "mongoose": "^4.11.12", "morgan": "~1.8.1", "pug": "~2.0.0-beta11", "serve-favicon": "~2.4.2" } }
Run the command to install the packages.
npm install
Set Up the Entry File
app.js
was created when you ran the generator command; however, you need to set up extra configuration. Edit the file to look like what I have below.
#app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); const session = require('express-session') const expressValidator = require('express-validator') const flash = require('connect-flash') const mongoose = require('mongoose') // 1 const genres = require('./routes/genres'); const books = require('./routes/books'); var app = express(); // 2 mongoose.Promise = global.Promise const mongoDB = process.env.MONGODB_URI || 'mongodb://127.0.0.1/tutsplus-library' mongoose.connect(mongoDB) // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // 3 app.use(session({ secret: 'secret', saveUninitialized: true, resave: true })) // 4 app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formParam = root while(namespace.length) { formParam += '[' + namespace.shift() + ']' } return { param : formParam, msg : msg, value : value } } })) // 5 app.use(flash()) app.use(function (req, res, next) { res.locals.messages = require('express-messages') next() }) // 6 app.use('/genres', genres); app.use('/books', books); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // 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'); }); module.exports = app;
- You required the two routes you will be making use of in building this application. You will create the routes file shortly. The required routes are assigned as values to two different variables which are used when setting up the middleware for your routes.
- You set Mongoose to use
global.Promise
. The variableMongoDB
is assigned theMONGODB_URI
of your environment or the path to your local mongo server. This variable is passed as an argument to connect to the running MongoDB server. - You set up session middleware using
express-session
. This middleware is important as you will be displaying flash messages in some parts of your application. - You set up middleware for validation. This middleware will be used to validate form input, ensuring that users of the application do not submit an empty form. The validation uses a package installed,
express-validator
. - You set up middleware which will come in handy when displaying flash messages. This middleware makes use of
connect-flash
. - The routes for the application are set up to make use of the routes file you required. Requests pointing to /genres and /books will make use of the genres and books routes files respectively. At this moment you have not created the routes files, but you will do that soon.
Book and Genre Model
The Book Model will make use of Mongoose Schema to define how the books will be structured. Create a directory called models, and a new file called Book.js. Here is what it looks like.
#models/Book.js const mongoose = require('mongoose') mongoose.Promise = global.Promise const Schema = mongoose.Schema const bookSchema = Schema({ name: { type: String, trim: true, required: 'Please enter a book name' }, description: { type: String, trim: true }, author: { type: String, trim: true, }, genre: [{ type: Schema.Types.ObjectId, ref: 'Genre' }] }) module.exports = mongoose.model('Book', bookSchema)
Here you have four fields. The last field is used to store the genre each book belongs to. The genre field here references the Genre model, which will be created next. That's why the type is set to Schema.Types.ObjectId
, which is where the ids of each referenced genre will be saved. ref
specifies the model you are referencing. Note that genre is saved as an array, meaning that a book can have more than one genre.
Let's go ahead a create the Genre model.
#models/genre.js const mongoose = require('mongoose') mongoose.Promise = global.Promise const Schema = mongoose.Schema const genreSchema = Schema({ name: { type: String, trim: true, required: 'Please enter a Genre name' } }) module.exports = mongoose.model('Genre', genreSchema)
For your Genre, you need just one field: name
.
Genre Index Route and View
For this tutorial, you will make use of two routes paths for your genre: a path to add new genres, and another that lists the genres you have. Create a file in your routes directory called genres.js.
Start by requiring all the modules you will be making use of.
#routes/genres.js var express = require('express'); var router = express.Router(); const mongoose = require('mongoose') const Genre = require('../models/Genre')
Next, drop in the route that handles the index file for your genres.
router.get('/', (req, res, next) => { const genres = Genre.find({}).exec() .then((genres) => { res.render('genres', { genres: genres }) }, (err) => { throw err }) });
This route gets called whenever requests are made to /genres. Here you call the find method on your Genre model to obtain all the genres that have been created. These genres are then rendered on a template called genres. Let's go ahead and create that, but first, update your layout.pug to look like this:
#views/layout.pug doctype html html head title= title link(rel='stylesheet', href='/stylesheets/style.css') link(rel='stylesheet', href='http://ift.tt/29gcylm') script(src='http://ift.tt/1XwG72U') script(src='http://ift.tt/2aHTozy') body .container-fluid block header nav.navbar.navbar-inverse .container-fluid .navbar-header button.navbar-toggle.collapsed(type='button', data-toggle='collapse', data-target='#bs-example-navbar-collapse-2') span.sr-only Toggle navigation span.icon-bar span.icon-bar span.icon-bar a.navbar-brand(href='#') Local Library #bs-example-navbar-collapse-2.collapse.navbar-collapse ul.nav.navbar-nav.navbar-right li a(href='/books') View Books li a(href='/books/add') Add New Book li a(href='/genres') View Genres li a(href='/genres/add') Add New Genre block content
This will give your views a nice structure to aid navigation. Now create a view file called genre.pug. In this file, you will loop through the genres created and output each genre in an unordered list.
Here is how the file should look.
#views/genres.pug extends layout block content h1 Genre ul.well.well-lg each genre, i in genres li.well.well-sm p #{genre.name}
Add New Genre Routes and View
Go back to your routes/genres.js to add the routes that will handle the creation of new genres.
#routes/genres.js // 1 router.get('/add', (req, res, next) => { res.render('addGenre') }) // 2 router.post('/add', (req, res, next) => { req.checkBody('name', 'Name is required').notEmpty() const errors = req.validationErrors() if (errors) { console.log(errors) res.render('addgenres', { genre, errors }) } const genre = (new Genre(req.body)).save() .then((data) => { res.redirect('/genres') }) .catch((errors) => { console.log('oops...') console.log(errors) }) }) // 3 module.exports = router;
- The job of this router is to simply display the page for adding new routes. This router gets called whenever requests are made to /genres/add path.
- This router handles the submission of the form. When the form is submitted, we check to ensure that a name is entered by the user. If no name is entered, the page is re-rendered. If the checks are good to go, the genre is saved and the user is redirected to the /genres page.
- The module is exported as a router.
Now you can go ahead and create the page for adding a new genre.
#views/addGenre.pug extends layout block content .row .col-md-12 h1 Add Book form(method="POST", action="/genres/add") .form-group label.col-lg-2.control.label Name .col-lg-10 input.form-control(type="text", name='name') .form-group .col-lg-10.col-lg-offset-2 input.button.btn.btn-primary(type='submit', value='Submit') if errors ul for error in errors li!= error.msg
Books Routes and View
Create a new route file for books, and name it books.js. As you did earlier with the genre, start by requiring the necessary modules.
#routes/books.js var express = require('express'); var router = express.Router(); const mongoose = require('mongoose') const Book = require('../models/Book') const Genre = require('../models/Genre')
Next, set up the router for displaying all the books saved in the library. Try that on your own in the way as you set up that of the genre; you can always check back to make corrections.
I guess you tried that out—here is how it should look.
router.get('/', (req, res, next) => { const books = Book.find({}).exec().then((books) => { res.render('books', { books: books }) }, (err) => { throw err }) });
When this router is called, a request is made to find all books saved in the database. If all goes well, the books are shown on the /books page, else an error is thrown.
You need to create a new file for displaying all books, and here is how it should look.
#views/books.pug extends layout block content h1 Books ul.well.well-lg each book, i in books li.well.well-sm a(href=`/books/show/${book.id}`) #{book.name} p= book.description
You simply loop through the books returned and output the name and description of each book using an unordered list. The name of the book points to the individual page of the book.
Add New Book Routes and View
The next router you set up will handle the addition of new books. Two routers will be used here: one will simply render the page, and another will handle the submission of the form.
This is how the routers look.
router.get('/add', (req, res, next) => { const genres = Genre.find({}).exec() .then((genres) => { res.render('addBooks', { genres }) }) .catch((err) => { throw err }) }) router.post('/add', (req, res, next) => { req.checkBody('name', 'Name is required').notEmpty() req.checkBody('description', 'Description is required').notEmpty() req.checkBody('genre', 'Genre is required').notEmpty const errors = req.validationErrors() if (errors) { console.log(errors) res.render('addBooks', { book, errors }) } const book = (new Book(req.body)).save() .then((data) => { res.redirect('/books') }) .catch((errors) => { console.log('oops...') }) })
In the first router, you are displaying the /addBooks page. This router is called when a request is made to /add path. Since books added are supposed to have genres, you want to display the genres that have been saved to the database.
const genres = Genre.find({}).exec() .then((genres) => {
The code above finds all the genres in your database and returns them in the variable genres. With this, you will be able to loop through the genres and display them as checkboxes.
The second router handles the submission of the form. First, you check the body of the request to ensure that some fields are not empty. This is where the express-validator
middleware you set in app.js comes handy. If there are errors, the page is re-rendered. If there are none, the new Book instance is saved and the user is redirected to the /books page.
Let's go ahead and create the views for this.
Create a new view file called addBooks.pug. Note that the name of the view matches the first parameter given to res.render. This is because you are rendering a template. During redirection, you simply pass the path you want to redirect to, as you did with res.redirect('/books')
.
Having established that, here is what the views should look like.
#views/addBooks.pug extends layout block content .row .col-md-12 h1 Add Book form(method="POST", action="/books/add") .form-group label.col-lg-2.control-label Name .col-lg-10 input.form-control(type="text", name='name') .form-group label.col-lg-2.control-label Author .col-lg-10 input.form-control(type="text", name='author') .form-group label.col-lg-2.control-label Book Description .col-lg-10 textarea#textArea.form-control(rows='3', name='description') .form-group label.col-lg-2.control-label Genre .col-lg-10 for genre in genres .checkbox input.checkbox(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked) label(for=genre._id) #{genre.name} .form-group .col-lg-10.col-lg-offset-2 input.button.btn.btn-primary(type='submit', value='Submit') if errors ul for error in errors li!= error.msg
The important thing to note here is the form action and method. When the submit button is clicked, you are making a POST request to /books/add. One other thing—once again you loop through the collection of genres returned and display each of them.
Book Show Route and View
Let us drop in the route to handle the requests made to each books page. While you are there, it is important to export your module too.
#routes/books.js router.get('/show/:id', (req, res, next) => { const book = Book.findById({ _id: req.params.id }) .populate({ path: 'genre', model: 'Genre', populate: { path: 'genre', model: 'Book' } }) .exec() .then((book) => { res.render('book', { book }) }) .catch((err) => { throw err }) }) module.exports = router;
No magic is happening here.
First, requests made to this router must have an id: the id of the book. This id is obtained from the params of the request using req.params.id
. This is used to identify the specific book that should be obtained from the database, as the ids are unique. When the book is found, the genre value of the book is populated with all the genres that have been saved to this book instance. If all goes well, the book view is rendered, else an error is thrown.
Let's create the view for a book. Here is how it should look.
block content .well.well-lg h1 #[strong Name:] #{book.name} ul li #[strong Description:] #{book.description} li #[strong Author]: #{book.author} li #[strong Genre:] each genre in book.genre #{genre.name} |,
You can start up your node server by running:
DEBUG=tutsplus-library:* npm start
Conclusion
Now you know how to build a standard web application in Node.js, not just a simple to-do app. You were able to handle form submission, reference two models, and set up some middleware.
You can go further by extending the application—try adding the ability to delete a book. First add a button to the show page, and then go to the routes files and add a router for this. Note that this is going to be a POST request.
You can also think of more features to add to the application. I hope you enjoyed it.
No comments:
Post a Comment