五、Express框架
5.1概念
Express框架是一个基于Node.js平台的极简、灵活的WEB开发框架:www.express.com.cn
简单来说,Express是一个封装好的工具包,封装了很多功能,便于我们开发WEB应用
5.2安装
npm i express
5.3 Express初体验
//01-express初体验.js
//1.导入exrpess
const express=require("express")//2.创建应用对象
const app=express()//3.创建路由
app.get("/home",(req,res)=>{res.end("Hello Express!")
})//4.监听端口
app.listen(9000,()=>{console.log('服务已启动,监听端口:9000')
})
启动服务
nodemon 01-初体验.js
通过过浏览器访问,就可以收到响应了
5.4路由的使用
格式:
app.<method>(path,callback)
示例:
//1.导入exrpess
const express=require("express")//2.创建应用对象
const app=express()//3.创建路由
app.get("/",(req,res)=>{//请求方式为"get",且路径是"/"res.end("home")
})
app.post('/login',(req,res)=>{//请求方式为"post",且路径是"/login"res.end('login')
})
app.get("/view",(req,res)=>{//请求方式为"get",且路径是"/view"res.end("view")
})
app.all("/text",(req,res)=>{//请求方不限,且路径是"/text"res.end('/text')
})
app.all("*",(req,res)=>{//请求方式不限,路径不限(以上路由都匹配时,执行这个路由)res.end('404 Not Found')
})//4.监听端口
app.listen(9000,()=>{console.log('服务已启动,监听端口:9000')
})
5.5获取请求报文参数
//1.导入exrpess
const express=require("express")//2.创建应用对象
const app=express()//3.创建路由
app.get("/home",(req,res)=>{//原生操作console.log('req.method:',req.method)console.log('req.url:',req.url)console.log('req.httpVersion:',req.httpVersion)console.log('req.headers',req.headers)//express操作console.log('req.path',req.path)console.log('req.query',req.query)console.log('req.ip',req.ip)console.log("req.get('host')",req.get('host'))res.end("home")
})//4.监听端口
app.listen(9000,()=>{console.log('服务已启动,监听端口:9000')
})
输出:
req.method: GET
req.url: /home?arg1=1&arg2=2
req.httpVersion: 1.1
req.headers {host: 'localhost:9000',connection: 'keep-alive','cache-control': 'max-age=0','sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"','sec-ch-ua-mobile': '?0','sec-ch-ua-platform': '"Windows"','upgrade-insecure-requests': '1','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7','sec-fetch-site': 'none','sec-fetch-mode': 'navigate',