Node.js学习笔记(三) Express框架(1)
Express框架(1)
文章目录
1. Express基本介绍以及安装
1.1 什么是Express
Express 是一个简洁而灵活的 node.js Web应用框架, 提供一系列强大特性帮助你创建各种Web应用。Express 不对 node.js 已有的特性进行二次抽象,我们只是在它之上扩展了Web应用所需的功能。丰富的HTTP工具以及来自Connect框架的中间件随取随用,创建强健、友好的API变得快速又简单
官方文档:http://www.expressjs.com.cn/
1.2 Express的安装
npm init -y
npm install express --save
2. Express HelloWorld
当访问http://localhost:3000 时控制台打印Hello World,并在浏览器中打印Hello World
var express = require("express");
//实例化express
var app = express();
app.get("/",function (req,res) {
console.log("Hello World");
res.send("Hello World");
});
//监听3000端口
app.listen(3000,function () {
console.log("http://localhost:3000 start~");
});
3. 文件操作路径和模块标识路劲问题
- 在node中对文件使用相对路径,相对的是从执行node命令的路径开始的
- 而模块标识路劲与文件操作路劲不同,它是以当前项目开始的
4. Node热加载
nodemon用来监视node.js应用程序中的任何更改并自动重启服务,使用nodemon启动node程序,nodemon将监视启动目录中的文件,如果有任何文件更改,nodemon将自动重新启动node应用程序。
安装nodemon
npm install -g nodemon
使用nodemon启动
nodemon xxx.js
5. 路由
5.1 路由概述
路由是指确定应用程序如何响应对特定端点的客户端请求,该请求是URI(或路径)和特定HTTP请求方法(GET,POST等)。每个路由都可以有一个或多个处理函数,这些函数在路由匹配时执行。
关于路由的官方文档:http://www.expressjs.com.cn/guide/routing.html
app.METHOD(PATH, HANDLER) //路由主要结构
// app 是一个实例express。
// METHOD 是一个HTTP请求方法,小写。
// PATH 是服务器上的路径。
// HANDLER 是路由匹配时执行的功能。
GET请求
app.get('/', function (req, res) {
res.send('Hello World!')
})
POST请求
app.post('/', function (req, res) {
res.send('Got a POST request')
})
PUT请求
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
DELETE请求
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})
5.2 路由路径匹配规则
Express使用path-to-regexp来匹配路径路径
path-to-regexp:https://www.npmjs.com/package/path-to-regexp
- 匹配根路径
/
app.get('/', function (req, res) {
res.send('root')
})
- 匹配
/about
app.get('/about', function (req, res) {
res.send('about')
})
- 匹配
/random.text
app.get('/random.text', function (req, res) {
res.send('random.text')
})
- 匹配
/acd
和/abcd
app.get('/ab?cd', function (req, res) {
res.send('ab?cd')
})
- 匹配
abcd
,abbcd
,abbbcd
,ab...cd
等等。
app.get('/ab+cd', function (req, res) {
res.send('ab+cd')
})
- 匹配
abcd
,abxcd
,abRANDOMcd
,ab123cd
,等
app.get('/ab*cd', function (req, res) {
res.send('ab*cd')
})
- 匹配
/abe
和/abcde
app.get('/ab(cd)?e', function (req, res) {
res.send('ab(cd)?e')
})
- 匹配其中包含
a
的任何内容
http://localhost:3000/bas ,http://localhost:3000/bdsdd/a等等
app.get(/a/, function (req, res) {
res.send('/a/')
})
- 匹配
butterfly
和dragonfly
,但不butterflyman
,dragonflyman
等
app.get(/.*fly$/, function (req, res) {
res.send('/.*fly$/')
})
- 获取路径参数,可以捕获在URL中的位置指定的值。捕获的值将填充在
req.params
对象中
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
路径参数的名称必须由“单词字符”([A-Za-z0-9_])组成。
由于连字符-
和点.
按字面解释,所以可以组合出多种匹配方式
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
在路径匹配中可以使用正则表达式更好的匹配数据,正则一般写在()
中
Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
5.3 路由处理
对于路由的处理不仅可以使用单个回调函数,还可以提供多个回调函数,其行为类似于中间件来处理请求。
唯一的例外是这些回调可能会调用next('route')
以绕过剩余的路由回调。您可以使用此机制对路径施加前置条件,然后在没有理由继续当前路由的情况下将控制权传递给后续路由。
- 单个函数处理
app.get('/example/a', function (req, res) {
res.send('Hello from A!')
})
- 多个函数处理,使用
next()
将控制权转交给下一个函数
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
5.4 API 方法
Express API 官方文档:http://www.expressjs.com.cn/4x/api.html
6. 静态文件映射
在express项目中,我们通常将公共资源文件放置在public
目录中
使用express中间件函数托管静态文件(图像,CSS , JavaScript 等),该函数类似于
express.static(root, [options])
- 通过如下代码就可以将
public
目录下的资源文件对外界公开
app.use(express.static('public'))
- 可以为公开资源提供虚拟路径,根据虚拟路劲访问公开资源
app.use('/static', express.static('public'))
- 由于提供给该
express.static
函数的路径是相对于启动node
进程的目录,如果从另一个目录运行express应用程序,则需要为其提供更为准确的路劲,这时候就需要使用__dirname
来拼接更安全的绝对路径
app.use('/static', express.static(path.join(__dirname, 'public')))
7.Express中使用模板引擎(art-template)
art-template官网
:https://aui.github.io/art-template/zh-cn/index.html
- 安装
npm install --save art-template
npm install --save express-art-template
- 例子
var express = require('express');
var app = express();
// 配置
app.engine('art', require('express-art-template'));
app.set('views','./views') //设置views视图渲染存储目录,如果不需要更改视图模板路径可以省略
//使用
app.get('/', function (req, res) {
res.render('index.art', {
user: {
name: 'aui',
tags: ['art', 'template', 'nodejs']
}
});
});
8. Express获取表单数据
由于Express中没有内置对post提交表单的解析方法,所以我们需要使用第三方中间件来解决post表单数据的获取解析功能
body-parser
是一个HTTP请求体解析中间件
,Express框架中就是使用这个模块做为请求体解析中间件。
- 安装
npm install body-parser
- 使用
var express = require("express");
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/test",function (req,res) {
console.log(req.body);
res.send(req.body)
})
app.listen(3000,function () {
console.log("start...");
})
结果: