express基础笔记

express第三方模块

npm i express
  1. 提供了方便简洁的路由定义方式
  2. 对获取http请求参数进行了简化操作
  3. 对模板引擎支持程度高,方便渲染动态html页面
  4. 提供了中间件,对请求的拦截
  5. 大量的第三方中间件对功能进行扩展

基本使用

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Loveyless

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

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

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

打赏作者

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

抵扣说明:

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

余额充值