- Node.js Blueprints
- Krasimir Tsonev
- 322字
- 2021-07-16 11:36:14
Getting acquainted with Express
Express (http://expressjs.com/) is a web application framework for Node.js. It is built on top of Connect (http://www.senchalabs.org/connect/), which means that it implements middleware architecture. In the previous chapter, when exploring Node.js, we discovered the benefit of such a design decision: the framework acts as a plugin system. Thus, we can say that Express is suitable for not only simple but also complex applications because of its architecture. We may use only some of the popular types of middleware or add a lot of features and still keep the application modular.
In general, most projects in Node.js perform two functions: run a server that listens on a specific port, and process incoming requests. Express is a wrapper for these two functionalities. The following is basic code that runs the server:
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
This is an example extracted from the official documentation of Node.js. As shown, we use the native module http
and run a server on the port 1337
. There is also a request handler function, which simply sends the Hello world
string to the browser. Now, let's implement the same thing but with the Express framework, using the following code:
var express = require('express'); var app = express(); app.get("/", function(req, res, next) { res.send("Hello world"); }).listen(1337); console.log('Server running at http://127.0.0.1:1337/');
It's pretty much the same thing. However, we don't need to specify the response headers or add a new line at the end of the string because the framework does it for us. In addition, we have a bunch of middleware available, which will help us process the requests easily. Express is like a toolbox. We have a lot of tools to do the boring stuff, allowing us to focus on the application's logic and content. That's what Express is built for: saving time for the developer by providing ready-to-use functionalities.
- Learning LibGDX Game Development(Second Edition)
- The Supervised Learning Workshop
- Beginning C++ Game Programming
- SoapUI Cookbook
- Python數據可視化:基于Bokeh的可視化繪圖
- C/C++算法從菜鳥到達人
- Learning AWS Lumberyard Game Development
- 基于免疫進化的算法及應用研究
- Processing互動編程藝術
- Python Network Programming Cookbook(Second Edition)
- Building Mapping Applications with QGIS
- 深入淺出RxJS
- Python Data Analysis Cookbook
- Learning Docker Networking
- PHP與MySQL權威指南