目录
3.3 连接数据库在config.default.js下添加
1发起axjx请求
我们使用axios框架发起axjx请求
1.1引入axios框架
<script src="./js/axios.min.js"></script>
1.2发起get/post请求
前端发起get请求
axios.get(`http://127.0.0.1:8081/getsession`)
.then(function (response) { // 处理成功情况
console.log(response);
})
.catch(function (error) { // 处理错误情况
console.log(error);
})
.then(function () { // 总是会执行
});
前端发起post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get(`http://127.0.0.1:7001/sendcode?tel=${regTel}`,{
withCredentials: true//允许跨域携带凭证(cookie)
})
2配置后端
2.1配置post请求的安全验证
在config.default.js下添加安全验证
config.security = {
csrf: {
enable: false,
ignoreJSON: true
}
}
2.2 配置允许跨域
这里需要在项目引入egg-cros 打开项目所在位置的命令行输入npm i egg-cors
在plugin.js添加跨域cors插件,
cors: {
enable: true,
package: 'egg-cors'
},
在config.default.js下添加
config.cors = {
// {string|Function}
origin: '*',//运行跨域
// {string|Array}
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'//请求方法
};
当允许前端携带cookies时
config.cors = {
// origin: '*', //允许的域,*代表所有的
origin: 'http://127.0.0.1:8080', //允许的域,*代表所有的
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',//允许跨域的请求方法
credentials: true//后端允许跨域携带cookie
};
3数据库连接与配置
3.1 引入数据库插件
npm i --save egg-mysql
3.2在plugin.js添加跨域数据库插件
mysql: {
enable: true,
package: 'egg-mysql',
},
3.3 连接数据库在config.default.js下添加
config.mysql = {
// 单数据库信息配置
client: {// host
host: '127.0.0.1', // 端口号
port: '3306',// 用户名
user: 'root',// 密码
password: 'root', // 数据库名
database: 'students',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
3.4解构app出来
const { ctx, app } = this;
在路由的controlle下面添加
let resust = await app.mysql.query()
完整代码如下
前端发起请求界面js
<script src="./js/axios.min.js"></script>
<script>
axios.get(`http://127.0.0.1:8081/setsession`)
.then(function (response) {
// 处理成功情况
console.log(response);
axios.get(`http://127.0.0.1:8081/getsession`)
.then(function (response) { // 处理成功情况
console.log(response);
})
.catch(function (error) { // 处理错误情况
console.log(error);
})
.then(function () { // 总是会执行
});
})
.catch(function (error) {
// 处理错误情况
console.log(error);
})
.then(function () {
// 总是会执行
});
后端路由界面
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/setsession', controller.home.setsession);
};
后端接口具体代码
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async setsession() {
const { ctx } = this;
ctx.session.id = 110
ctx.session.tel = 120
ctx.body = 'hi, egg';
}
}
}
module.exports = HomeController;
另一个接口操作数据库的代码
'use strict';
const { Controller } = require('egg');
class studentController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async addstudent() {
const { ctx, app } = this;
let clientdata = ctx.request.body
console.log('前端传递的数据', clientdata);
//连接数据库并且操作(添加学生)
// 添加之前应该先判断当前学生是否已经添加过
// INSERT INTO teachers VALUES ('王玲', '女', 25, '2017-05-10 12:00:20')
let resust_r = await app.mysql.query(`select * from student_info where stu_number=${clientdata.stu_num}`)
console.log(resust_r);
if (resust_r == 0) {
let resust = await app.mysql.query(
`INSERT INTO student_info
(stu_number, stu_name, stu_age,stu_bir, stu_phone, stu_adress)
VALUES ('${clientdata.stu_num}', '${clientdata.stu_name}', ${clientdata.stu_age},'${clientdata.stu_bir}','${clientdata.stu_tel}','${clientdata.stu_adress}')`);
if (resust.affectedRows == 1) {
ctx.body = {
code: 1,
data: '添加成功'
};
}
else {
ctx.body = {
code: -1,
data: '添加失败'
};
}
}
else {
ctx.body = {
code: 0,
data: '该学生已存在'
};
}
}
async getstudents() {
const { ctx, app } = this;
let resust = await app.mysql.query(`select * from student_info`)
ctx.body = {
code: 1,
data: resust
};;
}
async getstu() {
const { ctx, app } = this;
// 前端给后端传递的数据
let clientdata = ctx.request.query
console.log(clientdata);
// 连接数据库
let resust = await app.mysql.query(`select * from student_info where stu_number=${clientdata.stu_num}`)
console.log(resust);
ctx.body = {
code: 1,
data: resust
};
}
async delstu() {
const { ctx, app } = this;
// 前端给后端传递的数据(指定的标签)
let clientdata = ctx.request.query
console.log(clientdata.stu_num);
// 连接数据库
let resust = await app.mysql.query(` DELETE FROM student_info WHERE stu_number=${clientdata.stu_num};`)
console.log('操作数据库的结果', resust);
ctx.body = {
code: 1,
data: {}
};
}
}
module.exports = studentController;