概述
Express.js是基于node.js中http模块和connect组件的web框架,该框架提供了一个类似MVC的架构,为web应用提供了一个良好的架构(视图、路由、模型),可以省去很多开发人员需要做的繁琐的工作,比如根据http请求方式以及URL做路由解析、分析请求和相应数据等。
官网:http://www.expressjs.com.cn/
需要学习的对象

express
Application
Request
Response
Router
express
express 是一个方法也是一个对象 主要可以给我们生成一些中间件给我们使用 ,
如: static() 生成静态目录的中间件
如: urlencoded() 解析post方式提交数据的中间件
Application
管理服务器的对象,后续的管理操作都是基于这个对象去执行的
listen()
监听端口
app.listen(9001,function(){console.log('服务启动了...')})
get()
开启一个get 路由
参数1. 路径
参数2: 回调函数
回调函数有两个形参
形参1: req 请求对象 (后续讲)
形参2: res 响应对象 (后续讲)
app.get('/',function(req,res){res.send('ok')})
post
开启一个post路由
app.post('/demo',function(req,res){res.send('demo ok')})
中间件
每个路由都会经过中间件
使用use方法使用一个中间件
next方法是释放控制权
app.use(function(req,res,next){console.log('middle')next()})
设置静态目录
// 设置静态目录// 只要放在静态目录的,都可以通过浏览器地址栏访问到app.use(express.static(path.join(__dirname,'public')))
Request
req.query
表单
<form action="/saveuser" method="get">name:<input type="text" name="username"><br>password:<input type="text" name="pw"><br><input type="submit"></form>
路由中获取数据
app.get('/saveuser',function(req,res){// 获取get 提交过来的数据console.log(req.query)res.send('ok')})
req.params
获取路由参数
app.get('/test/:id',function(req,res){//req.params.idconsole.log(req.params)res.send('id:'+req.params.id)})
req.body
获取post方式提交过的数据
前提:
// 解析post方式提交过来的数据,然后就可以通过req.body获取app.use(express.urlencoded({extended:false}))
获取:
app.post('/saveu',function(req,res){// req.body获取post提交过来的数据,前提要设置urlencodedconsole.log(req.body)res.send('u ok')})
Response
res.send()
返回一个字符串
如果返回的是带有标签的,标签会被解析
app.get('/',function(req,res){res.send('<h1>ok</h1>')})
res.json()
返回一个json对象
//返回json对象app.get('/test1',function(req,res){res.json({status:'success',msg:'请求成功',data:[121,2,66,45,4,4,999]})})
res.redirect()
重定向
// 重定向 访问test2 跳转到/app.get('/test2',function(req,res){res.redirect('/')})
res.sendFile()
// 读到一个文件,把内容返回app.get('/test3',function(req,res){res.sendFile(path.join(__dirname,'test.txt'))})
res.download()
下载文件
app.get('/test4',function(req,res){res.download(path.join(__dirname,'test.txt.zip'))})
res.render
返回一个模板
前提要先设置模板引擎和模板目录:
app.set('view engine','ejs');app.set('views',path.join(__dirname,'views'))
app.get('/',function(req,res){// 参数1:模板的名称,它自己回去找模板目录对应名字的文件// 参数2: 需要返回到模板里面数据res.render('index',{name:'young',age:18})})
