nodejs express - yaokun123/php-wiki GitHub Wiki
Nodejs的express框架
一、什么是express?
express是基于node.js平台开发的一个“web开发框架”,就是一个node.js模块。
express提供了一系列强大的特性,帮助你创建各种Web和移动设备应用。
二、为什么学习express?
为了让我们基于Node.js开发web应用程序更高效。
三、express的特点
1、实现了路由功能
2、中间件功能(函数)
3、对req 和 res 对象的扩展
4、可以集成其他模板引擎
四、express基本使用
npm install express
//1、加载express模块
var express = require('express');
//2、创建一个app 对象(类似于创建一个server对象)
var app = express();
//通过中间件监听一个指定的路由的请求
app.get('/index',function(req,res){
res.end('hello world');
});
//3、启动服务
app.listen(9090,function(){
console.log('http://localhost:9090')
});
- 3、res.send() 和 res.end()区别
res.end('hello world你好世界');//中文乱码
res.send('hello world你好世界');//不会乱码
1、参数类型区别
res.send() 参数可以是 a Buffer object, a String, an object, or an Array
res.end() 参数类型只能是 Buffer 对象或者是字符串
2、res.send()会自动发送更多的响应报文头,其中就包括Content-Type:text/html;chartset=utf-8,所以没有乱码
- 4、app.get 和 app.use 和app.all 注册路由的区别
app.get/app.post
1、请求的方法必须是get/post。
2、请求路径的 pathname 必须等于(===)路由。
app.use('/index',function(){})
1、在进行路由匹配的时候不限定方法,什么请求方法都可以。
2、请求路径的第一部分只要与index相等即可,并不要求请求路劲完全匹配。
app.all('/inedx',function(){})
1、在进行路由匹配的时候不限定方法,什么请求方法都可以。
2、请求路径的 pathname 必须等于(===)路由。
app.get('/^\/index(\/.+)*$/i',function(){})
app.get('/news/:years/:month/:day',function(req,res){
res.send(req.params);
})
五、通过express模拟apache实现静态资源托管服务