Question

CS 602 Server Side development hw3 please explain and comment the following node.js code var express...

CS 602 Server Side development hw3 please explain and comment the following node.js code

var express = require('express');
var bodyParser = require('body-parser');
var handlebars = require('express-handlebars');

var app = express();

// setup handlebars view engine
app.engine('handlebars',
    handlebars({defaultLayout: 'main_logo'}));
app.set('view engine', 'handlebars');

// static resources
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Routing
var routes = require('./partb_routes/index');
app.use('/', routes);

app.use(function(req, res) {
    res.status(404);
    res.render('404');
});

app.listen(3000, function(){
console.log('http://localhost:3000');
});

0 0
Add a comment Improve this question Transcribed image text
Answer #1

We use Express to handle all of the repeat setup tasks associated with building a HTTP server, and spend more time focusing on getting the core logic and UI of our applications correct. It sets up a very simple Express project, configured to perform common backend tasks like parsing requests and serving a public directory for client-side assets.

Require is a powerful tool for looking up libraries and external dependencies within a Node.js project.

var express = require('express');
var bodyParser = require('body-parser');
var handlebars = require('express-handlebars');

When we pass a string to require, it will try to find a properly packaged CommonJS or native Node.js module, keeping a reference to the loaded module, and return it to the caller. Then, when we try to load the library again, the cached reference will be returned rather than attempting to load a fresh instance. This lets us efficiently manage dependencies and script loading with almost no effort. The first set is loading pre-packaged Node modules, installed using npm. Require first checks the project’s node_modules folder for these files, and then checks the global npm cache. The second set of require loads libraries local to the current project.

As we have resolved the issue of dependencies, we start initializing our Express project.

var app = express();

// setup handlebars view engine
app.engine('handlebars',
    handlebars({defaultLayout: 'main_logo'}));
app.set('view engine', 'handlebars');

// static resources
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Then we create our Express instance, but we also set up how we will be rendering our web pages and where to find them, and begin to set up the actual logic of the Express application.

Express is constructed on the concept of middleware functions, little functions that are capable of processing or responding to a request, or sending the request to the next piece of middleware capable of handling our request. We can use middleware to set up generic handling for all endpoints, specific handling for endpoints matching some route, or specialized handling for an individual endpoint. This is done primarily via the use function.

Use has a couple of nuances that allows us to set up complex server-wide handling easily. Looking at the use calls, we can see that some calls have passed a single argument, while others received two. The single argument call is applied for the selected piece of middleware to every request that reaches the server, while the two args version allows us to restrict the middleware to operating on a single route. We set up our pre-generated routes at the end of the call.

Next, we set up some custom middleware functions.

app.use(function(req, res) {
    res.status(404);
    res.render('404');
});

app.listen(3000, function(){
console.log('http://localhost:3000');
});

Again, there’s a lot going on in this series of calls, so let’s break down what’s happening. Middleware is eventually some function that will be executed, and these functions always get the same three arguments, in the same order. The first argument is the request object. The request object is where we will look to get some information about an individual request coming to the server. The request can be preproccessed by middleware, and since all parts of middleware receive the same object reference for a given request, all other parts of middleware will receive this information. That’s how the bodyParser library works. It allows JSON payloads to automatically be parsed and turned into a request body object, rather than plain text.

The second argument is the response object. It is used to do things like set HTTP status code, report request progress back to the client, and actually send our response to the client when we are done handling the request.

The third argument is the next object. It is a reference to the next function in the middleware stack. We call next to indicate that we have done attempting to handle this request, and that the next piece of middleware should make its attempt at handling.

When we take a look at the middleware added at the end of app.js, we have a single piece of standard middleware that handles any routes that do not have middleware set up to respond, and it returns a 404 which shows a not found message instead. The remaining middleware states the development and production error handlers. As we can see these are four-argument functions, and are as such error handling middleware. Since the first piece of error middleware sends a response, in the dev environment we will return an error message with full stack traces, whereas in production we merely notify the user that an error occurred.

Finally, on the last line of app.js, we export our Express application using the standard commonjs module.exports syntax.

// Routing
var routes = require('./partb_routes/index');
app.use('/', routes);

The way a router works is very similar to the way to how our base Express application works. We initialize an instance of our router, register some number of pieces of middleware, and export it to consumer.

Add a comment
Know the answer?
Add Answer to:
CS 602 Server Side development hw3 please explain and comment the following node.js code var express...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • CS 602 Server Side development hw1c please explain and comment the following html code <b>Employees with...

    CS 602 Server Side development hw1c please explain and comment the following html code <b>Employees with Last Name {{name}}</b> <hr/> <table border=1>     <tr><th>Id</th><th>First Name</th><th>Last Name</th></tr>     {{#each employees}}        <tr>           <td>{{this.id}}</td>           <td>{{this.firstName}}</td>           <td>{{this.lastName}}</td>        <tr>     {{/each}} </table> part two <!doctype html> <html> <head>    <title>CS602 HW2</title> </head> <body> <header>    <img src="/images/bu-logo.gif" alt="logo"> </header> <h3>CS602 HW2 - Your Name</h3> <a href="/addEmployee">Add Employee</a> <hr/>       {{{body}}} </body>...

  • !! Express.js quesiton !! I just started studying about Node.js with Express.js framework. I tried so...

    !! Express.js quesiton !! I just started studying about Node.js with Express.js framework. I tried so hard but I have no idea how to solve these questions... I hope you guys can help me to solve those questions. Thank you :) This is my problem : DELETE /book?title=:book_title always returns 204 Not Content status code even if the book is not present in the datastore. no response body. GET /books returns 200 Success status code. returns list of all books....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT