概述

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

需要学习的对象


image-20210914103537684.png
express
Application
Request
Response
Router

express

express 是一个方法也是一个对象 主要可以给我们生成一些中间件给我们使用 ,
如: static() 生成静态目录的中间件
如: urlencoded() 解析post方式提交数据的中间件

Application

管理服务器的对象,后续的管理操作都是基于这个对象去执行的

listen()

监听端口

  1. app.listen(9001,function(){
  2. console.log('服务启动了...')
  3. })

get()

开启一个get 路由
参数1. 路径
参数2: 回调函数
回调函数有两个形参
形参1: req 请求对象 (后续讲)
形参2: res 响应对象 (后续讲)

  1. app.get('/',function(req,res){
  2. res.send('ok')
  3. })

post

开启一个post路由

  1. app.post('/demo',function(req,res){
  2. res.send('demo ok')
  3. })

中间件

每个路由都会经过中间件
使用use方法使用一个中间件
next方法是释放控制权

  1. app.use(function(req,res,next){
  2. console.log('middle')
  3. next()
  4. })

设置静态目录

  1. // 设置静态目录
  2. // 只要放在静态目录的,都可以通过浏览器地址栏访问到
  3. app.use(express.static(path.join(__dirname,'public')))

Request

所有的请求提交过来的数据,都是通过这个对象去获取的

req.query

表单

  1. <form action="/saveuser" method="get">
  2. name:<input type="text" name="username">
  3. <br>
  4. password:<input type="text" name="pw">
  5. <br>
  6. <input type="submit">
  7. </form>

路由中获取数据

  1. app.get('/saveuser',function(req,res){
  2. // 获取get 提交过来的数据
  3. console.log(req.query)
  4. res.send('ok')
  5. })

req.params

获取路由参数

  1. app.get('/test/:id',function(req,res){
  2. //req.params.id
  3. console.log(req.params)
  4. res.send('id:'+req.params.id)
  5. })

req.body

获取post方式提交过的数据
前提:

  1. // 解析post方式提交过来的数据,然后就可以通过req.body获取
  2. app.use(express.urlencoded({extended:false}))

获取:

  1. app.post('/saveu',function(req,res){
  2. // req.body获取post提交过来的数据,前提要设置urlencoded
  3. console.log(req.body)
  4. res.send('u ok')
  5. })

Response

从服务端需要返回数据给客服端,都是通过这个对象完成

res.send()

返回一个字符串
如果返回的是带有标签的,标签会被解析

  1. app.get('/',function(req,res){
  2. res.send('<h1>ok</h1>')
  3. })

res.json()

返回一个json对象

  1. //返回json对象
  2. app.get('/test1',function(req,res){
  3. res.json({
  4. status:'success',
  5. msg:'请求成功',
  6. data:[121,2,66,45,4,4,999]
  7. })
  8. })

res.redirect()

重定向

  1. // 重定向 访问test2 跳转到/
  2. app.get('/test2',function(req,res){
  3. res.redirect('/')
  4. })

res.sendFile()

  1. // 读到一个文件,把内容返回
  2. app.get('/test3',function(req,res){
  3. res.sendFile(path.join(__dirname,'test.txt'))
  4. })

res.download()

下载文件

  1. app.get('/test4',function(req,res){
  2. res.download(path.join(__dirname,'test.txt.zip'))
  3. })

res.render

返回一个模板
前提要先设置模板引擎和模板目录:

  1. app.set('view engine','ejs');
  2. app.set('views',path.join(__dirname,'views'))
  1. app.get('/',function(req,res){
  2. // 参数1:模板的名称,它自己回去找模板目录对应名字的文件
  3. // 参数2: 需要返回到模板里面数据
  4. res.render('index',{name:'young',age:18})
  5. })