search
HomeWeb Front-endJS TutorialDetailed introduction to the installation and use of Node.js Express

This time I will bring you a detailed introduction to the installation and use of Node.js Express. What are the precautions for the installation and use of Node.js Express. The following is a practical case, let's take a look.

Install express

In order to rewrite our HelloWorld, we need to install the Express module. Express is a web framework based on Node.js. The official website is here: http://expressjs.com/. The official website’s introduction to Express is:

Fast, unopinionated, minimalist web framework for Node.js

Express is very lightweight and is usually used for web back-end development. There are some recommended books, you can see here: http://www.jb51.net/books/470249.html.

To install the express module, just use the npm command directly. Execute the npm command without parameters in the command line environment to see the npm help information. To install a Node.js module, use the install subcommand. "npm install xxx" will install the xxx module to the current path, and "npm install -g xxx" will install the xxx module to the global location of the current user. Use "npm helo install" to view the details of the install subcommand. To uninstall a module, use "npm uninstall xxx". If you are installing globally, use "npm uninstall -g xxx".

When you use npm to install a module, it will automatically resolve dependencies.

Execute the following command in the command line environment to install express:

npm install -g express –registry=https://registry.npm.taobao.org

Note that I specified the Taobao image, which is faster.

Special note:

I refer to the tutorial here: https://github.com/alsotang/node-lessons

Soon, you can See the following interface (note that the Express version we installed is 4.13.3):

Okay, Express is installed.

It should be noted that after using the -g command to globally install the Node.js module, you need to set the environment variable NODE_PATH, otherwise it may be reported when we use the node command to start an application. The specified module is not found. This error occurs. In my Windows 7 environment, the location of the npm module during global installation is "C:\Users\Administrator\AppData\Roaming\npm\node_modules" (see the picture above). As for the setting of environment variables, go to Computer->Advanced System Settings->Advanced->Environment Variables, add an environment variable named NODE_PATH, and set its value to the root directory of the global module. After the settings are completed, re-enter the command line environment to take effect.

Mention that if you want to add multiple module paths in NODE_PATH, just separate them with ";". For specific meaning, execute "node -h" on the command line to view the help.

HelloWorld

The code is as simple as:

// 引入 express 模块
var express = require('express');
// 创建 express 实例
var app = express();
// 响应HTTP的GET方法
app.get('/', function (req, res) {
 res.send('Hello World!');
});
// 监听到8000端口
app.listen(8000, function () {
 console.log('Hello World is listening at port 8000');
});

Save it as HelloExpress.js, and then execute "node HelloExpress.js" command, the website will be running. Visit it with a browser, it will be the same as the last example.

What is the difference between using Express

The code that does not use Express is purple:

// 引入http模块
var http = require("http"); 
// 创建server,指定处理客户端请求的函数
http.createServer(
  function(request, response) { 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write("Hello World!"); 
    response.end(); 
  }
).listen(8000); 
console.log("Hello World is listening at port 8000");

Use the above code directly The http module provided by Node.js creates an HTTP server and specifies a function to handle requests. In actual application, we need to distinguish different HTTP requests within this function, such as GET, HEAD, POST, etc. The Express version of HelloWorld is different. It can specify a response function for each path and HTTP request. For example, the Express version of HelloWorld instance will only respond when you enter "http://localhost:8000" in the browser. Return "HelloWorld", if you enter "http://localhost:8000/abc" in the browser, you will see an error message (you will receive a 404 status code , express will automatically handle it for you). There is a concept of URL routing here. If you modify the code to look like this:

app.get('*', function (req, res) {
 res.send('Hello World!');
});

The effect will be similar to the version using the http module. Because I used "*" as a wildcard, it can match any path. Express's get method prototype is as follows:

app.METHOD(path, callback [, callback …])

For details, please refer here: http://expressjs.com/4x/api.html#app.METHOD.

Use express to create HelloExpress

express模块有一个命令行工具express,可以用来生成基于express模块的应用结构(网站结构)。

express 4.x之后,express命令被独立出来放在了express-generator模块中。我们用下面的命令全局安装express这个命令行工具:

npm install -g express-generator

安装完成后,在命令行环境下执行“express -V”,可以看到express的版本是4.13.1。

好了,现在我们使用express命令来创建一个默认的网站。

在命令行环境下导航到myprojects这个目录下,执行下面的命令:

express HelloExpress

然后可以看到:

仔细看上面的图哦,它告诉了我们三类非常重要的信息:

  1. express命令创建的网站的目录结构以及创建的文件

  2. 安装依赖(进入到HelloExpress下,执行npm install)

  3. 使用npm start启动网站(express 4.x后)

好啦,我们先安装依赖。这里要先提一下HelloExpress目录下的package.json文件,其内容如下:

{
 "name": "HelloExpress",
 "version": "0.0.0",
 "private": true,
 "scripts": {
  "start": "node ./bin/www"
 },
 "dependencies": {
  "body-parser": "~1.13.2",
  "cookie-parser": "~1.3.5",
  "debug": "~2.2.0",
  "express": "~4.13.1",
  "jade": "~1.11.0",
  "morgan": "~1.6.1",
  "serve-favicon": "~2.3.0"
 }
}

这个文件定义了一个Node.js应用的基本信息,我们这次注意的是 dependencies ,它定义了应用依赖的模块。

在HelloExpress下执行“npm install”命令,npm会自动找到package.json,分析它,安装所有依赖模块。这要花费一些时间,休息一下,去喝杯茶。

看看,下面是安装结果:

G:\nodejs\myprojects\HelloExpress>npm install
debug@2.2.0 node_modules\debug
└── ms@0.7.1
cookie-parser@1.3.5 node_modules\cookie-parser
├── cookie-signature@1.0.6
└── cookie@0.1.3
serve-favicon@2.3.0 node_modules\serve-favicon
├── fresh@0.3.0
├── etag@1.7.0
├── parseurl@1.3.0
└── ms@0.7.1
morgan@1.6.1 node_modules\morgan
├── basic-auth@1.0.3
├── on-headers@1.0.0
├── depd@1.0.1
└── on-finished@2.3.0 (ee-first@1.1.1)
body-parser@1.13.3 node_modules\body-parser
├── content-type@1.0.1
├── bytes@2.1.0
├── depd@1.0.1
├── on-finished@2.3.0 (ee-first@1.1.1)
├── qs@4.0.0
├── iconv-lite@0.4.11
├── http-errors@1.3.1 (inherits@2.0.1, statuses@1.2.1)
├── raw-body@2.1.2 (unpipe@1.0.0)
└── type-is@1.6.6 (media-typer@0.3.0, mime-types@2.1.4)
express@4.13.3 node_modules\express
├── escape-html@1.0.2
├── merge-descriptors@1.0.0
├── array-flatten@1.1.1
├── cookie@0.1.3
├── cookie-signature@1.0.6
├── methods@1.1.1
├── utils-merge@1.0.0
├── range-parser@1.0.2
├── fresh@0.3.0
├── path-to-regexp@0.1.7
├── vary@1.0.1
├── content-type@1.0.1
├── etag@1.7.0
├── parseurl@1.3.0
├── content-disposition@0.5.0
├── serve-static@1.10.0
├── depd@1.0.1
├── qs@4.0.0
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-er
rors@1.3.1)
├── accepts@1.2.12 (negotiator@0.5.3, mime-types@2.1.4)
├── type-is@1.6.6 (media-typer@0.3.0, mime-types@2.1.4)
└── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
jade@1.11.0 node_modules\jade
├── character-parser@1.2.1
├── void-elements@2.0.1
├── commander@2.6.0
├── constantinople@3.0.2 (acorn@2.1.0)
├── mkdirp@0.5.1 (minimist@0.0.8)
├── clean-css@3.3.7 (commander@2.8.1, source-map@0.4.4)
├── uglify-js@2.4.24 (uglify-to-browserify@1.0.2, async@0.2.10, source-map@0.
1.34, yargs@3.5.4)
├── with@4.0.3 (acorn@1.2.2, acorn-globals@1.0.5)
├── transformers@2.1.0 (css@1.0.8, uglify-js@2.2.5, promise@2.0.0)
└── jstransformer@0.0.2 (is-promise@2.0.0, promise@6.1.0)
G:\nodejs\myprojects\HelloExpress>

有兴趣的可以研究下各个依赖模块的信息,现在我们启动网站了。执行 npm start 命令,很快就可以看到下面的图:

看到上图,说明网站已正常运行。你可以在浏览器里访问http://localhost:3000,然后就可以看到这个页面:

OK,大功告成。

这个由express generator创建的HelloExpress和我们基于express手动写的HelloWorld又有一些不同,比如你在浏览器地址栏里输入http://localhost:3000/abc,就会看到一个默认的404页面,显示了具体的错误信息。而我们的HelloWorld,显示的则是“Cannot GET /abc”这个文本串。这就是模板的便利之处,有很多默认处理,可以为我们省很多麻烦。

Express版本的文件服务器

express是在Node.js的http的基础上实现的,相比http模块,封装更多更适用于web服务器场景的功能。之前我们在Node.js开发入门——HTTP文件服务器里使用http模块实现了一个简单的文件服务器。那个版本的文件服务器还有一个缺陷,就是没有根据文件名设置HTTP的Content-Type头部。如果我们使用express来实现文件服务器(用到了Request对象的sendFile方法),哈哈,就只有几行代码,还解决了Content-Type问题!

代码如下:

var express = require('express');
var app = express();
app.get('*', function(req, res){
  res.sendFile(req.path, {root: dirname+'/', dotfiles: 'deny'});
});
app.listen(3000);

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用node前端模板引擎Jade标签

怎样进行Vue拖拽组件开发

The above is the detailed content of Detailed introduction to the installation and use of Node.js Express. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)