前端、后端联系知识梳理
- 以打开浏览器,访问login为栗
- 打开浏览器,访问localhost:8080/#/login
- src/router/index.js 会根据 /login 找到对应的Login(src/components/pages/Login.vue)组件, 然后渲染到浏览器
- 当输入用户名和密码,点击登录按钮后
- 根据Login组件中配置的axios请求向后端发送请求.
- 请求的url是: http://localhost:3001/login
- 后端监听该url的代码如下
const Router = require('koa-router');
let router = new Router();router.post('/login', async(ctx)=>{// 此处是逻辑实现代码
})
- 后端监听到该路由请求后,会用请求的参数和数据库进行比对.
- 使用mongoose连接数据库的代码如下
const mongoose = require('mongoose');
const { resolve } = require('path');
const db = 'mongodb://localhost/smile-vue'exports.connect = () =>{mongoose.connect(db);let maxConnectTimes = 0;return new Promise((resolve, reject) =>{mongoose.connection.on('disconnected', (err) =>{// 断线重连,最大重连次数3次if(maxConnectTimes <= 3){maxConnectTImes++;mongoose.connect(db);} else{reject(err);throw new Error('[connect error] 数据库连接失败')}});// 失败mongoose.connection.in('error', () =>{console.log('[error] 数据库出错');mongoose.connect(db);})// 成功打开mongoose.connection.once('open', () =>{console.log('[ok] MongoDB connected successfully');resovle();})})
}
const glob = require('glob');
const { resolve } = require('path');export.initSchemas = () =>{glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require);
}
// 此时,会连接到数据库,并初始化各个表的规则.
const User = mongoose.model('User');User.findOne({ userName: username }).exec().then(async (result) =>{console.log(result);
})
ctx.body = {code:200,message:msg
}