1.创建egg项目并启动后端服务器
javascript
pnpm create egg //创建项目
//选择simple就行
pnpm i //下载插件
pnpm run dev //运行项目
2.安装跨域依赖和数据库依赖
javascript
pnpm i egg-cors //跨域依赖
pnpm i egg-mysql //数据库依赖
pnpm i egg-scripts //部署
3.修改配置文件 plugin.js
javascript
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
mysql:{
enable:true,
package:'egg-mysql'
},
cors:{
enable:true,
package:'egg-cors'
}
};
4.配置config.default.js
javascript
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1709895338474_7197';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
//关闭CSRF验证 跨域请求 不进行同源验证
config.security = {
csrf:{
enable:false
}
}
config.cors = {
origin: '*',
allowMethods: 'GET,POST,PUT,DELETE' //设置允许访问的请求方式
}
//配置数据库连接
config.mysql = {
app:true,
client:{
host:'localhost', //数据库地址
port:'3306', //数据库端口号
user:'root', //数据库用户名
password:'123456', //数据库密码
database:'mitest', //要连接的数据库
}
}
return {
...config,
...userConfig,
};
};
5.配置service层
javascript
const Service = require("egg").Service;
class CustomerService extends Service {
//4.登录(根据客户手机号码和密码进行查询)
async selectCustomerByTelIdByPass(customer) {
let result;
try {
//调用数据库实现查询
let sql = `select * from customer where telId=${customer.telId} and password=${customer.password}`;
result = await this.app.mysql.query(sql);
} catch (error) {
console.log(error)
}
return result;
}
}
module.exports = CustomerService;
6.配置controller层
javascript
const { Controller } = require("egg");
class CustomerController extends Controller {
//1.全查询所有的商品分类信息
async selectCustomerByTelIdByPass() {
const { ctx } = this; //对应的application实例 全局
//调用service层方法得到结果 返回给前台
const result = await this.ctx.service.customer.selectCustomerByTelIdByPass(this.ctx.request.body);
ctx.body = result
}
}
module.exports = CustomerController
7.配置路由层
javascript
router.post('/selectUserByUserByPass' , controller.userinfo.selectUserByUserByPass)