Hello World ExampleIn this chapter, to help you get your feet wet using Express.js, we’ll build the quintessential programming example—the Hello World app.. The topics covered in this ch
Trang 1Hello World Example
Trang 2Hello World Example
In this chapter, to help you get your feet wet using Express.js, we’ll build the
quintessential programming example—the Hello World app If you’ve already built some variation of this Express.js app (perhaps by following an online tutorial), feel free to skip to the next chapter and go either to Chapter 3 for the API methods and objects, or to Chapter 19-22 for examples The topics covered in this chapter are as follow:
● Getting started: creating the minimal Express.js app from scratch
● Generator commands: command-line options of Express.js Generator
● MVC structure and modules: a common way to organize code for Express.js apps
● Watching for file changes: a development tip
Trang 3Hello World Example
Getting Started
I’ve always liked the bottom-up approach to teaching, starting from the most basic concepts and progressing toward more complex ones Also, I’ve noticed that
developers gain more confidence when they learn how to create something from scratch instead of just modifying an existing project or using boilerplate
To begin, you’ll write a web server that runs locally on port 3000 So, when you open the http://localhost:3000 location in the browser, you should see Hello World The number 3000 is the de-facto standard port number for Express.js applications
Trang 4Hello World Example
The file hello.js server will utilize Express.js; therefore, let’s include this library:
var express = require('express');
Now we can create an application (i.e., instantiate an Express.js object):
var app = express();
The web server will run locally on port 3000, so let’s define it here: var port = 3000; Next, let’s define a wildcard route (*) with the app.get() function:
app.get('*', function(request, response){
resquest.end('Hello World');
});
Trang 5Hello World Example
The app.get() function accepts regular expressions3 of the URL patterns in a
string format In our example, we’re processing all URLs by specifying the wildcard
* character
In the case of Express.js, you can use RegExps in routes to define complex URL patterns dynamically To find out more about regular expressions, check out the documentation at https://developer.mozilla.org/en-US/docs/
Web/JavaScript/Guide/Regular_Expressions
Trang 6Using Request Handlers
The second parameter to the app.get() method is a request handler A typical
Express.js request handler is similar to the one we pass as a callback to the
native/core Node.js http.createServer() method For those unfamiliar with the core http module, a request handler is a function that will be executed every time the server receives a particular request, usually defined by an HTTP method (e.g., GET) and the URL path (i.e., the URL without the protocol, host, and port) The Express.js request handler needs at least two parameters—request, or simply req, and response, or res (more on this later in Chapter 9) Similarly to their core
counterparts, we can utilize readable and writable streams interfaces
(http://nodejs.org/api/stream.html) via response.pipe() and/or response.on('data', function(chunk) { })
Trang 7Outputting Terminal Messages
Finally, we start the Express.js web server and output a user-friendly terminal
message in a callback: app.listen(port, function(){ console.log('The server is
running, ' + ' please, open your browser at http://localhost:%s', port); }); To run the script, we execute $ node hello.js from the project folder You should see “The server is running, please open your browser at http://localhost:3000
Now, if you open your browser at http://localhost:3000 (same as
http://127.0.0.1:3000, http://0.0.0.0:3000, or http://localhost:3000/), you should see the Hello World message no matter what the URL path is (see Figure 2-2) The URL path is the string after the domain and port, so for http://localhost:3000/, it is / and for http://localhost:3000/messages/ is it “/messages/” When you use “*” in the route definition, this path doesn’t matter
Trang 8Full Code
The full code of the hello.js file is provided here for your reference:
var express = require('express');
var port = 3000;
var app = express();
app.get('*', function(request, response){
resquest.end('Hello World');
});
app.listen(port, function(){
console.log('The server is running, ' + ' please open your browser at http://localhost:%s', port); });
Trang 9Enhancing the App
Enhancing the App We can make our example a bit more interactive by echoing the name that
we provide to the server along with the “Hello” phrase To do so, we can copy the hello.js file with $ cp hello.js hello-name.js and add the following route right before the all-encompassing route (all.get('*', )) from the previous example:
app.get('/name/:user_name', function(req,res) {
res.status(200);
res.set('Content-type', 'text/html');
res.send('' + 'Hello ' + req.params.user_name + '' + '' ); });
Inside of the /name/:name_route route, we set the proper HTTP status code (200 means OK) and HTTP response headers and wrap our dynamic text in HTML body and h1 tags.
Trang 10The full source code of the hello-name.js file is provided next (and is also available in the downloadable source code for this book):
var express = require('express');
var port = 3000;
var app = express();
app.get('/name/:user_name', function(request,response) {
response.status(200); response.set('Content-Type', 'text/html');
response.end('' + 'Hello ' + req.params.user_name + '' + '' );
});
app.get('*', function(request, response){
response.end('Hello World');
});
app.listen(port, function(){
console.log('The server is running, ' + ' please open your browser at http://localhost:%s', port);
});
Trang 11After shutting down the previous server and launching the hello-name.js script, you’ll be able to see the dynamic response; for example, entering
http://localhost:3000/name/azat in your browser
So far we’ve created two Express.js apps from scratch Each of them was just a few lines of code This should give you the confidence, and illustrate how easy it
is, to create web servers with Express.js and Node.js! But there’s an even faster way—Express.js generator Let’s cover its commands and options