- 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.
- Production Ready OpenStack:Recipes for Successful Environments
- Learn WebAssembly
- Instant Ext.NET Application Development
- Java:High-Performance Apps with Java 9
- Python機(jī)器學(xué)習(xí)之金融風(fēng)險(xiǎn)管理
- Hands-On Kubernetes on Windows
- Programming Microsoft Dynamics? NAV 2015
- Instant Automapper
- 計(jì)算機(jī)系統(tǒng)解密:從理解計(jì)算機(jī)到編寫高效代碼
- 微服務(wù)設(shè)計(jì)
- Python機(jī)器學(xué)習(xí)技術(shù):模型關(guān)系管理
- Objective-C入門教程
- Unity 5.x 2D Game Development Blueprints
- Unity 2017 Game Optimization(Second Edition)
- 零基礎(chǔ)玩轉(zhuǎn)Python