当前位置: 首页 > Web前端 > vue.js

Koa&Mongoose&Vue实现前后端分离--04服务器注册&登录:用户路由配置

时间:2023-03-31 20:10:46 vue.js

上一节回顾mongoose连接数据库数据存储结构定义后端:路由拦截Postman:测试接口准备npmi-S@koa/router//安装路由和路由拦截的基本用法//修改文件:/server/app.jsconstkoa=require('koa');constRouter=require('@koa/router');//导入NPM包constrouter=newRouter()//创建实例constapp=newkoa();app.use((ctx,next)=>{ctx.body='testtesttest';//这个中间件任何时候both都会走。当GET请求'/'路径时,return会被后面的return覆盖,所以next();})router.get('/',(ctx,next)=>{//拦截GET请求访问'/'路径ctx.body=`访问路径:${ctx.originalUrl}`});app.use(router.routes()).use(router.allowedMethods());//嵌入中间件app.on('error',err=>{log.error('servererror',err)});module.exports=app;使用nodemon配置的launch.json运行浏览器并输入localhost:3000和localhost:3000/any以查看输出。优化代码这里我们希望将所有的路由配置提取到/server/router文件中(注意恢复/server/app.js)。//新建文件:/server/control/users.js——预定义处理路由处理函数asyncfunctionlist(ctx){ctx.body='list'}asyncfunctionregister(ctx){ctx.body='register'}asyncfunctionlogin(ctx){ctx.body='login'}asyncfunctionupdate(ctx){ctx.body='update'}module.exports={list,register,login,update}//创建一个新的文件:/server/router/users.jsconstRouter=require('@koa/router');constrouterUtils=require('../utils/router');const{list,register,login,update}=require('../control/users');constrouter=newRouter({prefix:'/users'//路由前缀,该文件下的路由路径,追加'/users'asprefix});//配置路由constroutes=[{path:'/',method:'GET',handle:list},{path:'/',method:'POST',handle:login},{path:'/:id',method:'PATCH',handle:update},];routerUtils.register.call(router,routes);//注册路由module.exports=router;//导出用户的路由实例//创建一个新文件:/server/utils/router.jsfunctionregister(routes){//转为'@koa/router'拦截形式route:router.get(,)routes.forEach((route,idx)=>{const{path,method,handle}=route;this[method.toLowerCase()](path,async(ctx,next)=>{awaithandle(ctx);})})}module.exports={register,}//新建文件:/server/router/index.jsconstuserRouter=require('./users');//导出中间相关到User路由组件,后面可以添加其他中间件routes=require('./router');constapp=newkoa();app.use((ctx,next)=>{ctx.body='TestTestTest';next();})//中间件:路由-->不支持一次注册多个中间件//app.use(...router.routes).use(...router.allowedMethods);routes.forEach(route=>{app.use(route);});app.on('error',err=>{log.error('servererror',err)});module.exports=app;Postman测试接口可以创建文件夹存放同一系列的请求,或者您可以直接创建e用于测试Get请求/用户界面的新请求。可以通过断点查看拦截请求参考文档@koa/router