node笔记之express路由

一、web服务器简介

1.web服务器的功能

  • 接受http请求(GET、POST、DELETE、PUT、PATCH)
  • 处理http请求(自己处理或交给其他程序处理)
  • 做出响应(返回页面、文件、各类数据)

2.常见web服务器架构

  • Nginx/Apache:负责接收HTTP请求,确定谁来处理请求,并返回请求的结果
  • php-fhm/php模块:处理分配给自己的请求,并将处理结果返回给分配者

3.常见请求种类:

  • 请求文件:包括静态文件(网页、图片、JS、CSS文件),以及由程序处理得到的文件
  • 完成特定的操作:如登陆、获取特定数据等

4.node的web服务器

  • 不依赖其他特定的web服务器软件(如Apache、Nginx、IIS)
  • 直接对请求进行逻辑处理
  • 可以对web服务器各种配置(类似于apache要配置.ini文件)

二、使用http模块创建web服务器

http模块是nodejs的核心(原生)模块

1
2
3
4
5
6
7
8
//引入http模块
var http=require('http');
//创建服务器
var webServer=http.creatServer(fuction(req,res){
res.end('hello');
});
//设置服务器监听端口
webServer.listen(6000);

三、使用express创建web服务器

1.创建服务器

1
2
3
4
5
6
7
8
9
10
11
12
//引入express模块
var express=require('express');
//创建express实例
var app=express();
//设置基础路由
app.get('/',function (req,res) {
res.end('hello');
});
//监听端口
app.listen(3000,function () {
console.log('running at 3000')
});

2.静态文件服务器

通过Express唯一内置的中间件express.static可以方便地托管静态文件,例如图片、CSS、JavaScript 文件等。

1
2
3
app.use(express.static('./public'));
//表明基于public路径
//这样访问public目录下的index.html输入Url的时候就是http://localhost:3000/index.html

3.express里路由实现的三种方法

路由:
app.METHOD(PATH, HANDLER)

  • 将不同的请求,分配给相应的处理函数
  • 区分方式:根据路径或请求方法

path方法(路由路径)

要点是app.+v. 例如app.get,app.post,app.put,app.delete

1
2
3
4
5
6
7
8
//以主页上的 Hello World! 进行响应:
app.get('/', function (req, res) {
res.send('Hello World!');
});
//对 /user 路由的 PUT 请求进行响应:
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});

Router方法(express.Router)

使用 express.Router 类来创建可安装的模块化路由处理程序。Router 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。

一般用于这种情况,都是基于某一个路由下
http://example.com/post/add
http://example.com/post/list

1
2
3
4
5
6
7
8
9
10
var Router=express.Router();
//例如都基于post这个路由
Router.get('/add',function(req,res){
res.end('Router /add');
});
Router.get('/list',function(req,res){
res.end('Router /list');
});
//添加基础路径
app.use('/post',Router);

route方法(app.route)

用于同一路由下的不同处理,可用作链式路由

1
2
3
4
5
6
7
8
9
//例如article下不同处理
//发起post或get请求
app.route('/article')
.get(function (req,res) {
res.end('route /article get');
})
.post(function (req,res) {
res.end('route /article post');
});

路由参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//http://example.com/news/123
//123就是路由参数
//express里借助param方法
app.param('newsId',function (req,res,next,newsId) {
//把newsId直接存储在请求对象里
req.newsId=newsId;
next();
});
app.get('/news/:newsId',function (req,res) {
res.end('newsId:'+req.newsId)
})
app.listen(3000,function () {
console.log('running at 3000')
});
//localhost://3000/news/123

links:使用 Express 创建 Web 服务器 & express官方文档