Express-Node.js的web开发框架

本文详细介绍Express框架的安装、基本路由、静态服务配置、表单数据获取、模板引擎配置及使用,涵盖中间件、session插件等核心功能。

Express中文指南

API参考手册

第三方中间件大全

安装

npm install --save express

hello world

var express = require('express')

var app = express()

app.use(express.static('./public/'))

app.get('/', function (req, res) {
  res.send('hello world')
})

app.listen(3000, function () {
  console.log('express app is running ...')
})

基本路由

get:

app.get('/', function (req, res) {
  res.send('hello world')
})

post:

app.post('/', function (req, res) {
  res.send('Got a POST request')
})

静态服务

// /public资源
app.use(express.static('public'))

// /file资源
app.use(express.static('file'))

// /public/xxx
app.use('/public',express.static('public'))

// /static/xxx
app.use('/static',express.static('public'))

// /static/x
app.use('./static',express.static(path.join(_dirname,'public')))

在Express中获取表单GET请求参数

Express内置了一个API,可以通过req.query来获取

req.query

在Express中获取表达POST请求体数据

在Express中没有内置获取表单POST请求体的API,这里我们需要第三方包:body-parser
安装:

npm install --save body-parser

配置:

var express = require('express')
//0. 引包
var bodyParser = require('body-parser')
var app = express()

//配置 body-parser'
//只要加入了这个配置,则在req请求对象上会多出来一个属性:body
//也就是说你可以通过req.body来获取表单POST请求体数据
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())

使用:

app.use(function(req,res){
    res.setHeader('Content-Type','text/plain')
    res.write('you posted:\n')
    //可以通过req-body来获取表单POST请求体数据
    res.end(JSON.stringify(req.body,null,2))
})

在Express中配置使用express-art-template模板引擎

art-template-GitHub仓库
art-template 官方文档

  1. 安装
npm install --save art-template
//普通的
npm install --save express-art-template 
//搭配express使用的模板引擎
  1. 配置
    配置使用 art-template 模板引擎
    第一个参数,表示,当渲染以 .art 结尾的文件的时候,使用 art-template 模板引擎
//第一个参数用来配置视图的后缀名,这里是art,则你存储在views目录中的模板文件必须是xxx.art
//app.engine('art',require('express-art-template'))

//这里我们把art改为html
app.engine('html', require('express-art-template'))
  1. 使用
    Express 为 Response 相应对象提供了一个方法:render
    render 方法默认是不可以使用,但是如果配置了模板引擎就可以使用了
    res.render(‘html模板名’, {模板数据})
    第一个参数不能写路径,默认会去项目中的 views 目录查找该模板文件
    也就是说 Express 有一个约定:开发人员把所有的视图文件都放到 views 目录中
app.get('/', function (req, res) {
  res.render('index.html', {
     title: 'hello world'
  })
})

如果想要修改默认的 views视图渲染存储目录,可以

// 注意:第一个参数views千万不要写错
app.set('views', 目录路径)

express-session插件

在 Express 这个框架中,默认不支持 Session 和 Cookie
但是我们可以使用第三方中间件:express-session 来解决

  1. 安装npm install express-session
  2. 配置 (一定要在 app.use(router) 之前)
	var app = express()
	app.set('trust proxy', 1) // trust first proxy
	app.use(session({
	 // 配置加密字符串,它会在原有加密基础之上和这个字符串拼起来去加密
     // 目的是为了增加安全性,防止客户端恶意伪造
     // 相当于这样加密=》md5(md5(body.password)+'itcast')
	  secret: 'itcast',
	  resave: false,
	  // 无论你是否使用 Session ,我都默认直接给你分配一把钥匙,默认是true
	  saveUninitialized: true,
	  cookie: { secure: true }
	}))
  1. 使用
    当把这个插件配置好之后,我们就可以通过 req.session 来发访问和设置 Session 成员了
   //添加 Session 数据:
   req.session.foo = 'bar'
   
   // 访问 Session 数据:
   req.session.foo

注:session默认是在内存存储的,服务器一旦重启就会丢失,真正的生产环境会把session进行持久化存储

Express 中间件

概念

中间件的本质就是一个请求处理方法,我们把用户从请求到响应的整个过程分到多个中间件去处理,这样做的目的是提高代码的灵活性,动态可扩展。

参数

中间件本身是一个方法,该方法接收三个参数:

  • Request 请求对象
  • Response 响应对象
  • next 下一个中间件
next参数

当请求进来,会从第一个中间件开始进行匹配,如果匹配,则进来;
如果请求进入中间件之后,没有调用 next 则代码会停在当前中间件;
如果调用了 next 则继续向后找到第一个匹配的中间件, 如果不匹配,则继续判断匹配下一个中间件。

案例1:

var express = require('express')
var fs = require('fs')

var app = express()

app.use(function (req, res, next) {
  console.log(1)
  next()
})

app.get('/abc', function (req, res, next) {
  console.log('abc')
  next()
})

app.get('/abc', function (req, res, next) {
  console.log('abc 2')
})

app.get('/abc', function (req, res, next) {
  console.log('abc 3')
})

app.listen(3000, function () {
  console.log('app is running at port 3000.')
})

访问http://127.0.0.1:3000

1

访问http://127.0.0.1:3000/abc

1
abc
abc2

案例2:

var express = require('express')
var app = express()

app.get('/abc', function (req, res, next) {
console.log('abc')
req.foo = 'bar'
next()
})

app.get('/abc', function (req, res, next) {
console.log(req.foo)
console.log('abc 2')
})

app.listen(3000, function () {
console.log('app is running at port 3000.')
})

访问http://127.0.0.1:3000/abc,控制台打印

abc
bar
abc2
中间件分类
  1. 应用程序级别中间件
    万能匹配(不关心任何请求路径和请求方法)
app.use(function (req, res, next) {
  console.log("1")
  next()
})

以’/xxx/'开头的

app.use('/a', function (req, res,) {
   console.log('/ 2')
})
  1. 路由级别中间件

get:

app.get('/', function (req, res, next) {
     res.send('get')
     next()
})

post:

app.post('/', function (req, res) {
     res.send('post')
})

put:

app.put('/user', function (req, res) {
     res.send('put')
})

delete:

app.delete('/user', function (req, res) {
     res.send('delete')
})
  1. 错误处理中间件
    错误处理中间件详细用法
app.use(function (err, req, res, next) {
    console.error(err.stack)
    res.srarus(500).send('err')
  })

详细案例:

var express = require('express')
var fs = require('fs')

var app = express()

app.get('/', function (req, res, next) {
  fs.readFile('.d/sa./d.sa/.dsa', function (err, data) {
    if (err) {
      // return res.status(500).send('Server Error')
      // 当调用 next 的时候,如果传递了参数,则直接往后找到带有四个参数的应用程序级别中间件,3个参数也不匹配
      // 当发生错误的时候,我们可以调用 next 传递错误对象
      // 然后就会被全局错误处理中间件匹配到并处理之
      next(err)
    }
  })
})

app.get('/a', function (req, res, next) {
  fs.readFile('./abc', function (err, data) {
    if (err) {
      // return res.status(500).send('Server Error') 
      next(err)
    }
  })
})

//错误处理不会跳到这里,因为是3个参数
app.use(function (req, res, next) {
  res.send('404')
})

// 配置错误处理中间件
app.use(function (err, req, res, next) {
  res.status(500).send(err.message)
})

app.listen(3000, function () {
  console.log('app is running at port 3000.')
})
  1. 内置中间件
  1. 第三方中间件
    第三方中间件大全
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值