一、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
| 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
| var express=require('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'));
|
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
| app.get('/', function (req, res) { res.send('Hello World!'); }); 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(); 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
| 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
| app.param('newsId',function (req,res,next,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') });
|
links:使用 Express 创建 Web 服务器 & express官方文档