【Express】初识 Express 和路由

在Express中,路由用于确定应用程序如何响应客户端对特定端点(URL)的请求。简单来说,路由就是根据请求的URL和HTTP请求方法,执行相应的处理函数来处理请求和生成响应,默认是 GET 请求。

在Express中,可以使用app.get()app.post()app.put()app.delete()等方法来定义路由。这些方法的第一个参数是要匹配的URL路径,第二个参数是处理请求的回调函数(可以有多个回调函数)。回调函数接收请求对象(req)和响应对象(res)作为参数,可以根据需要对请求进行处理,并生成相应的响应。

路由路径和请求方法一起定义了请求的端点,它可以是字符串、字符串模式或者正则表达式。

1. 初识 express

创建一个文件夹,创建一个文件server.js,然后 npm init 创建 package.json。再然后 npm i express 安装express 模块。

下面是一个简单的Express路由的示例:

// index.js
// 1. 导入 express
const express = require('express');
// 2. 创建应用对象
const app = express();
// 3. 创建路由
app.get('/', (req, res) => {
  res.send(`
  <html>
    <h1>标签</h1>
  </html>
  `);
});
// /loginok 和 /logiok 都可以访问
app.get('/login?ok', (req, res) => {
  res.send({
    name: 'xiuxiu',
    age: 18
  })
})
// :id 占位符(:xx)  /user/2132 都可以访问
app.get('/user/:id', (req, res) => {
  console.log(req.params.id)  // 获取具体的路由参数id  id要与占位符名字相同
  res.send('ok');
});
// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function (req, res) {
  res.send('ab+cd');
});
// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function (req, res) {
  res.send('ab*cd');
});
// 还可以匹配正则表达式  例如以 fly 结尾的
app.get(/.*fly$/, function (req, res) {
  res.send('/.*fly$/');
});
app.post('/home', (req, res) => {
  res.send('home')
})
// 任何请求都可以
app.all('/test',(req,res)=> {
  res.send('test')
})
// 其他请求匹配不了的 404
app.all('*',(req,res)=> {
  res.send('404')
})
// 4. 监听端口,启动服务
app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

传入多个回调函数:

// 多个回调函数
app.get('/home', (req, res, next) => {
  console.log("验证token,cookie是否过期")
  // 调用 next 方法即可继续执行下一个回调函数
  next();
}, (req, res) => {
  // 查询数据库,返回数据
  res.send({ list: [1, 2, 3] })
})

另一种写法:

const cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

const cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb1, cb2])

接收前端传过来的参数:

  • req.query get 请求传过来的参数GET http://localhost:3000/list?a=1&b=2 HTTP/1.1

  • req.body post 请求传过来的参数,需要 app.use(express.json()) 中间件的解析
    在这里插入图片描述

  • req.params 动态参数(占位符处的参数)GET http://localhost:3000/user/996 HTTP/1.1

2. 路由拆分

const express = require('express')

const app = express()
app.get('/', (req, res) => {
  res.send('hello world')
})

const user = express.Router()
user.get('/list', (req, res, next) => {
  res.send('/list')
})
const goods = express.Router()
goods.get('/goods', (req, res, next) => {
  res.send('/goods')
})
app.use('/user', user)
app.use('/goods', goods)
app.listen(3000, () => {
  console.log("服务已启动...")
})
GET http://localhost:3000/user/list HTTP/1.1

3. 处理 404 和 500

放在所有路由后面。

// 500
app.use((err, req, res, next) => {
  res.status(500).render('500')
})
// 404  放最后!
app.use('*', (req, res) => {
  res.status(404).render('404', { url: req.originalUrl })
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值