基本方法
-
下面所有的app都可以进行修改,app指的是定义的网站服务器,路径都是使用默认localhost:3000路径 导入模块 require("express") 创建网站服务器 let app = express() 监听端口 app.listen(3000) 网页访问 http://localhost:3000
请求
-
get请求
-
app.get("路径",(req,res) => { })
-
all请求,可以获取任意格式的请求
-
app.all("路径",(req,res) => { })
请求api
-
req.body 获取请求体 req.path 获取请求地址 req.query 获取请求传递过来的参数
响应api
-
res.status(288) 设置返回状态码 res.send(数据) 设置返回的数据
中间件
-
app.use("/",(req,res,next) => {next()}) 请求参数处理,处理完可以根据next进行接着往下处理,也可以直接send返回
错误处理
-
抛出错误 throw new Error("程序发生了未知错误") 同步错误处理 app.use((err,req,res,next) => {res.status(500).send("服务器发生错误")}) 引入异步错误处理模块 require("util").promisify 异步错误处理 app.get('/',async (req,res,next) => {}) 异步错误try和catch try{await 容易发生错误的代码} chatch(ex){next(ex)}
设置跨域
-
res.setHeader('Access-Control-Allow-Origin', '*');
路由参数静态访问
-
创建路由 express.Router() 获取get参数 req.query 引入获取post参数模块 require("body-parser") 规定请求方式 app.use(bodyParser.urlencoded({extended:false})) 获取post参数 req.body 路由参数 app.get("/index/:id/:name/:age",(req,res) => {res.send(req.params)}) 静态资源访问 app.use(express.static("静态资源路径"))
解决history模式下访问404的问题
-
//下载第三方包 npm install connect-history-api-fallback //引入这个包 const history = require('connect-history-api-fallback') //调用这个函数,用在静态资源托管之前 app.use(history())
模块拼接
-
模块拼接引入模块 app.engine("art",require("express-art-template")) 模块存放位置 app.set("文件名",path.join(__dirname,"文件名")) 默认后缀 app.set("view engine",'默认后缀名') 模块拼接 res.render('路径',{msg:'message'}) 公共资源 app.locals.名称=[公共值]