node框架express

路由的概念

路由就是一个映射关系,匹配访问的对象和执行的函数,在生活中路由器有一个网线和若干个输出,当连接路由器的用户需要网络时,路由器会根据不同的用户匹配,然后将数据传递给用户,路由也是这样,当收到请求时,根据路由的映射关系,执行不同的函数,返回不同的内容。路由通过访问方法,访问路径,和处理函数三个方法确定

static静态资源托管

express提供use方法实现静态资源托管,可以通过指定目录名访问另一个指定目录下的所有文件,两个目录名可以不同

const express=require('express');
// 1.创建服务
const app=express();
// 托管静态资源,当访问路径以/public/开头时,去./public/目录下寻找
// 第一个参数可以省略
app.use(express.static('./public/'))

内部应该是通过获取访问路径,然后处理后进行文件读取操作

在express中使用模板引擎

1.安装需要的模块

安装

npm install --save art-template
npm install --save express-art-template

express-art-template是专门在express中吧art-template整合到express中的,依赖art-template包
配置

//第一个参数是指定模板的后缀名
app.engine('art',require('express-art-template'))

使用

// express为response对象提供了一个方法:render
// render方法默认不可以使用,配置模板引擎之后可以用
// 用set方式修改默认路径
app.set('views','指定默认路径')
app.get('/admin',function(req,res){
    // res.send('hello express')
    // 默认会去view文件夹  中寻找名为404.art的文件,这个寻找路径和URL无关
    res.render('admin/index.art',{
        name:'world'
    })
})

用express重构服务器

// 用express重构服务器
const express=require('express')
const app=express()
// 渲染的数组
const lists=[`<li>我是评论1</li>`,`<li>我是评论2</li>`]
app.engine('html',require('express-art-template'))
// 设置public为指定路径
app.set('views','public')
app.get('/',function(req,res){
    // res.send('hello express')
    // 默认会去view文件夹  中寻找名为404.art的文件,这个寻找路径和URL无关
    // 渲染留言列表
    res.render('index.html',{
        lists
    })
})
app.get('/write',function(req,res){
    res.render('write.html')
})
app.get('/handle',function(req,res){
    lists.push(`<li>${req.query.txt}</li>`)
    // express提供redirect重定向
    res.redirect('/')
})
// 托管public文件夹下的静态资源
app.use(express.static('./public/'))
app.listen(3000,function(){
    console.log('express is running');
})

在express中获取post请求数据

express中获取post请求数据需要引入一个中间件名为body-parser
1.配置

npm i --save body-parser

2.使用

// 引入中间件
const bodyParser =require('body-parser')
// 配置body-parser插件
app.use(bodyParser.urlencoded({extend:false}))
app.use(bodyParser.json())

3.使用

console.log(req.body);//{ txt: '123123' }
// 配置body-parser后req请求对象上会多一个属性body
// 可以直接通过req.body来获取表单的post数据

这个第三方包不建议使用,因为express提供了解析post请求的方法
点击这里了解详情

在express中获取GET请求数据

express内置了一个对象,可以直接通过req.query来获取
1.使用

req.query
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值