文章目录
express第三方模块
npm i express
- 提供了方便简洁的路由定义方式
- 对获取http请求参数进行了简化操作
- 对模板引擎支持程度高,方便渲染动态html页面
- 提供了中间件,对请求的拦截
- 大量的第三方中间件对功能进行扩展
基本使用
npm i express
const express = require("express")
const app = express() //创建服务器不需要在调用http下的 createServer
app.listen(3000); //监听端口
进阶
const express = require("express")
const app = express()
const mongoose = require("mongoose");
const { send } = require("process");
mongoose.connect("mongodb://localhost/playground")
.then(res=>{
console.log("数据库连接成功");
})
const User = mongoose.model("User", new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
},
age: {
type: Number,
min: 18,
max: 80,
},
password: String,
email: String,
hobbies: [String],
}))
app.get("/",(req,res)=>{
res.status(404).send(User.find()) //status设置状态码
//这里响应用res.send会
//检测响应内容的类型
//自动设置编码
//自动设置状态码
})
app.listen(3000);
console.log("服务器启动成功");
拿到get请求参数req.query
拿到post请求参数
需要第三方包 body-parser
const express = require("express")
const bodyParser = require("body-parser")
//配置
//true使用qs模块处理 false则用node系统模块querystring
app.use(express.urlencoded({extended:false}))
app.use(express.json())
app.post("/",(req,res)=>{
res.send(req.body)
})
静态资源处理 express.static
const express = require("express")
const app = express()
const path = require("path")
//判断是否时访问资源请求 如果不是内部调用next()检测下一个中间件
app.use(express.static(path.join(__dirname,"public")))
//或者直接
app.use(express.static(__dirname+'public'))
//现在public下的文件就可以访问了
//http://localhost:3000/vue.js
//http://localhost:3000/apple.jpg
//http://localhost:3000/css/test.css
//http://localhost:3000/banner.png
app.listen(3000)
console.log("连接ok");
中间件 进行拦截验证登陆态
next
默认匹配到就不会匹配了 必须调用next方法
app.get("/request",(req,res,next)=>{
req.name = "张三";
next();
})
app.get("/request",(req,res)=>{
res.send(req.name);
})
app.use接受所有的请求,或者接送某一个路径的所有请求
这里要调用next 要不然会卡住
app.use((req,res,next)=>{
next();
})
app.use("/list",(req, res, next) => {
next();
})
错误处理中间件
这样只能处理同步代码的错误
app.get("/index",(req,res)=>{
//抛出自带的错误函数
throw new Error("Error")
})
//发生错误时会执行
//err就是错误对象
app.use((err,req, res, next) => {
res.status(500).send(err.message)
})
异步代码的错误
app.get("/index",(req,res,next)=>{
fs.readFile("./不存在的文件.txt","utf8",(err,res)=>{
if(err != null){
next(err) //next传递参数那么就代表要触发错误处理中间件
} //不传的化匹配下面的规则
})
})
//发生错误时会执行
//err就是错误对象
app.use((err,req, res, next) => {
res.status(500).send(err.message)
})
——————————————————————————————————————————————————————————
app.get("/index",(req,res,next)=>{
fs.readFile("./jquery-3.5.0.js","utf8",(err,result)=>{
if(err != null){
next(err); //next传递参数那么就代表要触发错误处理中间件
}else{
res.send(result);
}
})
})
//发生错误时会执行
//err就是错误对象
app.use((err,req, res, next) => {
res.status(500).send(err.message)
})
应用
app.use可以写在最后面 匹配不存在的 返回404
promisify包装异步函数 try catch捕获错误
try catch能捕获同步或者异步代码 但是其他api的无法捕获 比如回调函数 promise对象
包装
const promisify = require("util").promisify;
const readFile = promisify(fs.readFile)
app.get("/index", async (req, res, next) => {
try { //如果try里面的代码出错 会跳到catch里面执行
await readFile("/aaa.js")
} catch(ex){
next(ex); //不报错所以不会中断
}
})
app.use((err, req, res, next) => {
res.status(500).send(err.message)
})
构建模块化路由
const express = require("express")
//创建路由对象
const home = express.Router()
//将路由和请求路径进行匹配
app.use("/home",home)
//在home下继续创建路由
home.get("/index", (req,res)=>{
// /home/index
res.send("你好")
})
http://localhost:3000/home/index