Home > Web Front-end > JS Tutorial > Detailed explanation of the installation and usage steps of Node.js Express

Detailed explanation of the installation and usage steps of Node.js Express

php中世界最好的语言
Release: 2018-05-22 10:36:01
Original
3107 people have browsed it

This time I will bring you a detailed explanation of the installation and use steps 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.

Previously we wrote a HelloWorld website directly after installing Node.js. This time, we use Node.js's Web framework Express to rewrite HelloWorld and see what the difference is. At the same time, we will also rewrite the previous file server with more complete functions and simpler code.

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
Copy after login

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');
});
Copy after login

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");
Copy after login

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!');
});
Copy after login

效果就和使用http模块的版本类似了。因为我使用了“*”作为通配符,可以匹配任何路径。Express的get方法原型如下:

app.METHOD(path, callback [, callback …])
Copy after login

具体可以参考这里:http://expressjs.com/4x/api.html#app.METHOD。

使用express创建HelloExpress

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

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

npm install -g express-generator
Copy after login

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

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

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

express HelloExpress
Copy after login

然后可以看到:

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

  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"
 }
}
Copy after login

这个文件定义了一个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>
Copy after login

有兴趣的可以研究下各个依赖模块的信息,现在我们启动网站了。执行 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);
Copy after login

是不是超级简单?

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

推荐阅读:

table表格内对某列内容进行搜索筛选步骤详解

Vue拖拽组件开发步骤解析

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template