node.js前后端交互,需要的技术

本文详细展示了Node.js中使用Egg.js框架进行前后端交互的实现,包括获取请求参数、数据库操作(增删改查)、文件上传等。涉及到的关键技术包括Controller、Service、Router以及MySQL数据库的查询和更新操作。同时,还涵盖了日期格式转换、正则表达式验证和前端伪链接的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

node.js前后端交互,需要的技术

1、xxxcontroller.js

const Controller = require("egg").Controller;

class TestController extends Controller {
	//获取请求参数
	getParam(key) {
		//得到请求方式: "GET","POST"
		let method = this.ctx.request.method;//"GET", "POST"
		if(method == 'GET') {
			let v = this.ctx.request.query[key];
			return v;
		}else if(method=="POST"){
			let v = this.ctx.request.body[key];
			return v;
		} 
	}
	
	async getStr() {
		try {
			this.ctx.response.body = "Hello Egg!";
		}catch(e) {
			console.log(e);
			this.ctx.response.body = "异常";
		}
	}
    
    
	async getAllStuByClazzId() {
		//获取请求参数clazzid
		let clazzid = this.getParam('clazzid');
		let list = await this.ctx.service.stuService.getAllByClazzId(clazzid);
		this.ctx.response.body = list;
	}
    
	//注册
	async registStu() {
		//获取参数
		let no  = this.getParam("no")
		let pwd = this.getParam("pwd");
		let name = this.getParam("name");
		let sex = this.getParam("sex");
		let hight = this.getParam("hight");
		let remark = this.getParam("remark");
		let birth = this.getParam("birth");
		let clazzid = this.getParam("clazzid");
		const files = this.ctx.request.files;
		
		let flag = await this.ctx.service.stuService.countNo(no);
		if(flag==true) {//要注册的新账号参数no,在表中已经存在了。
			this.ctx.response.body = "NO";
		}else {//注册
			// console.log("数据", no,pwd,name,sex,hight, remark, birth, clazzid);
			let num = await this.ctx.service.stuService.regist(no,pwd,name,sex,hight, remark, birth, clazzid,files);
			this.ctx.response.body = num;
		}
	}
    
	//根据学生的id删除学生,返回删除了多少条记录
	async delStuById() {
		let id = this.getParam("stuid");
		let num = await this.ctx.service.stuService.del(id);
		this.ctx.response.body = num;
	}
    
    //修改学生
	async updateStu() {
		let stuid = this.getParam("stuid")
		let no = this.getParam("no");
		let pwd = this.getParam("pwd");
		let name = this.getParam("name");
		let hight = this.getParam("hight");
		let remark = this.getParam("remark");
		let birth = this.getParam("birth");
		let sex = this.getParam("sex");
		let newclazzid = this.getParam("newclazzid");
		//如果前端没有修改头像,则files的值为 [] 
		const files = this.ctx.request.files;//[{file}]
		
		let num = await this.ctx.service.stuService
		 .updateStu(stuid,no, pwd,name,hight,remark,birth,sex,newclazzid,files)
		this.ctx.response.body = num;
	}
    
    //管理员登陆
	async adminlogin() {
		//得到前端的no和pwd
		let no = this.getParam("no");
		let pwd = this.getParam("pwd");
		//调用service层方法adminloginx()
		//list=[] or [{id:1,no:'www',pwd:'123',name:'小王'}];
		let list = await this.ctx.service.adminService.adminloginx(no,pwd);
		if(list.length==1) {//登陆成功
			this.ctx.session.no = list[0].no;
		} 
		this.ctx.response.body = list;
	}
	//判断是否登陆
	async checkadminlogin() {
		if(this.ctx.session.no) {//已经登陆
			this.ctx.response.body = true
		}else {//未登陆
			this.ctx.response.body = false
		}
	}
	//退出登陆
	async adminLoginOut() {
		this.ctx.session.no=null;
		this.ctx.response.body = true;
	}
    //查出所有的班级
	async getAllClazz() {
		//list是班级的对象数组
		let list = await this.ctx.service.clazzService.getAll();
		this.ctx.response.body = list;
	}
	
	//根据关键字模糊查询出班级
	async getCalzzByKey() {
		let key = this.getParam("key");
		//list是班级的对象数组
		let list = await this.ctx.service.clazzService.getByKey(key);
		this.ctx.response.body = list;
	}
	//根据班级id删除班级
	async delClazzById() {
		//得到客户端参数班级id
		let clazzId = this.getParam("id");
		// console.log(clazzId);
		let num = await this.ctx.service.clazzService.delById(clazzId);
		// 成功删除了多少条记录响应到客户端
		this.ctx.response.body = num;
	}
	//增加班级
	async addClass() {
		let newName = this.getParam("newName")
		let newMajor = this.getParam("newMajor")

		// console.log(newName, newMajor);
		let num = await this.ctx.service.clazzService.addClass(newName, newMajor)
		this.ctx.response.body = num;//响应增加了多条记录
	}
	
	//修改专业 major
	async updateMajor() {
		//被修改的班级的主键 id 值
		let clazzId = this.getParam("clazzId");
		//新的专业值
		let nmajor = this.getParam("newmajor");
		let num = await this.ctx.service.clazzService.updateMajor(clazzId,nmajor);
		this.ctx.response.body = num;//响应修改了多条记录
	}
    
    //根据学生的id值,查看当前学生的成绩
	async getStuGrade() {
		try {
			let stuid = this.getParam("stuid");
			let mylist = await this.ctx.service.gradeService.queryGrade(stuid);
			this.ctx.response.body = {state:1, list:mylist};
		}catch(e) {
			console.log(e);
			this.ctx.response.body = {state:-1};
		}
	}
    
}
module.exports = TestController;

1.1获取服务器端的参数

let no = this.getParam("no");
let pwd = this.getParam("pwd");

2、xxxService.js

const Service = require('egg').Service;

class AdminService extends Service {
	//登陆
	async adminloginx(no,pwd) {
		const sql = "select id, no, pwd, name from admin where no=? and pwd=?";
		//list=[] or [{id:1,no:'www',pwd:'123',name:'小王'}];
		let list = await this.ctx.app.mysql.query(sql, [no, pwd]);
		return list;
	}
    //查出所有的班级
	async getAll() {
		const sql = "select id, name, major from clazz";
		let list= await this.ctx.app.mysql.query(sql);
		return list;
	}
	//根据关键字查询
	async getByKey(key) {
		const sql = "select id,name,major from clazz where name like ? or major like ?";
		let list= await this.ctx.app.mysql.query(sql,[`%${key}%`,`%${key}%`]);
		return list;
	}
	
	//根据班级id删除班级
	async delById(id) {
		const sql = "delete from clazz where id=?";
		let r = await this.ctx.app.mysql.query(sql,[id]);
		// console.log(r);
		return r.affectedRows;//返回删除了多少条记录
	}
	
	//增加班级
	async addClass(myname, mymajor) {
		const sql = "insert into clazz(name,major)values(?,?)";
		let r = await this.ctx.app.mysql.query(sql,[myname, mymajor]);
		// console.log(r);
		return r.affectedRows;//返回增加了多少条记录
	}
	
	//修改专业 major
	async updateMajor(id, newmajor) {
		const sql = "update clazz set major=? where id=?";
		let r = await this.ctx.app.mysql.query(sql,[newmajor, id]);
		// console.log(r);
		return r.affectedRows;//返回修改了多少条记录
	}
    //根据学生的id值,查出学生的成绩单
	async queryGrade(stuid) {
		const sql = "select grade.id gradeid, courseid, stuid, name, score from grade inner join course on course.id=grade.courseid and stuid=?";
		//[{gradeid:1, courseid:23, stuid:13,name:'小王',score:0},{gradeid:2, courseid:24, stuid:13,name:'小王',score:0},....]
		let list = await this.ctx.app.mysql.query(sql,[stuid]);
		return list;
	}
	//根据班级id查询出所,该班级的所有学生
	async getAllByClazzId(clazzId) {
		const sql = "select id,no,pwd,name, sex, hight, remark,birth,clazzid,headimg from stu where clazzid=?";
		let list = await this.ctx.app.mysql.query(sql,[clazzId]);
		return list;
	}
	//统计表中是否有重复的账号, 有返回true,没有返回false
	async countNo(no) {
		const sql = "select count(*) nonum from stu where no=?";
		//list:其中一定是有仅只有一个对象 list=[{nonum:0}] 或 [{nonum:1}]
		let list = await this.ctx.app.mysql.query(sql, [no]);
		if(list[0].nonum==0) {//账号不重复
			return false;
		}else {//要注册的新账号参数no,在表中已经存在了。
			return true;
		}
	}
	
	//学生注册
	async regist(no,pwd,name,sex,hight, remark, birth, clazzid,files) {
		let file = files[0];
		const toFileName = '/public/upload/' + Date.now() + file.filename;
		let to = path.dirname(__dirname) + toFileName;
		await fs.copyFileSync(file.filepath, to);
		await fs.unlinkSync(file.filepath);//文件上传结束
		//上传的文件的网络访问路
		const headimg = "http://localhost:7001" + toFileName;
		
		const sql = "insert into stu(no,pwd,name, sex, hight, remark,birth,clazzid,headimg)values(?,?,?,?,?,?,?,?,?)";
		let res = await this.ctx.app.mysql.query(sql,[no,pwd,name, sex, hight, remark,birth,clazzid,headimg]);
		return res.affectedRows; 
	}
	
	async del(stuid) {
		const sql = "delete from stu where id=?";
		let r = await this.ctx.app.mysql.query(sql,[stuid]);
		return r.affectedRows;	
	}
	
	//修改学生, 有一个小问题, no是不需要修改的.
	async updateStu(stuid,no, pwd,name,hight,remark,birth,sex,newclazzid,files) {
		//文件上传到的url
		let url = null;
		if(files.length==1) {//有文件上传
			let file = files[0];
			const toFileName = '/public/upload/' + Date.now() + file.filename;
			let to = path.dirname(__dirname) + toFileName;
			await fs.copyFileSync(file.filepath, to);
			await fs.unlinkSync(file.filepath);//文件上传结束
			url = "http://localhost:7001" + toFileName;
		} 
		if(url==null) {//没有文件上传,不需要修改头像的地址 headimg
			let sql = "update stu set pwd=?,name=?,hight=?,remark=?,birth=?,sex=?,clazzid=? where id=?"
			let res = await this.ctx.app.mysql.query(sql,[pwd,name,hight,remark,birth,sex,newclazzid,stuid])
			return res.affectedRows;
		}else {
			let sql = "update stu set headimg=?, pwd=?,name=?,hight=?,remark=?,birth=?,sex=?,clazzid=? where id=?"
			let res = await this.ctx.app.mysql.query(sql,[url,pwd,name,hight,remark,birth,sex,newclazzid,stuid])
			return res.affectedRows;
		}
	}
   
    
}
module.exports = AdminService;

2.1获取数据库里的账号和密码

const sql = "select id, no, pwd, name from admin where no=? and pwd=?";
let list = await this.ctx.app.mysql.query(sql, [no, pwd]);
retutn list;

2.2根据关键字查询

const sql = "select id,name,major from clazz where name like ? or major like ?";

let list= await this.ctx.app.mysql.query(sql,[`%${key}%`,`%${key}%`]);

return list;

2.3根据id 删除

const sql = "delete from clazz where id=?";
let r = await this.ctx.app.mysql.query(sql,[id]);
// console.log(r);
return r.affectedRows;//返回删除了多少条记录
}

2.4增加元素

const sql = "insert into clazz(name,major)values(?,?)";
let r = await this.ctx.app.mysql.query(sql,[myname, mymajor]);
// console.log(r);
return r.affectedRows;//返回增加了多少条记录
}

3、xxxrouter.js

 
  //http://localhost:7001/xxx.do

router.get("/getAllStuByClazzId.do", controller.stuController.getAllStuByClazzId)

  //带文件上传,只能使用post
  router.post("/registStu.do", controller.stuController.registStu);
1.数据库中日期类型显示到前端后,显示格式需要转换
let dt = new Date(dt);//转换成了Date的对象
dt.getFullYear();//年
dt.getMonth()+1;月
dt.getDate();日
dt.getHours()时
dt.getMinutes()分
dt.getSeconds()秒

2.正则表达式对象的创建
let reg = /^字符数量字符数量字符数量$/
数量可省,省去数量后,默认值为1

let reg = /^[012]\.\d{1,2}$/
let falg  = reg.test(字符串);
flag值为true或false,表示字符串是否符合正则表达式对象

3. 伪连接,当按钮用的。示例中当点“退出登陆”后,会触发loginout()方法的执行.
<a href="javascript:loginout()">退出登陆</a>

(dt);//转换成了Date的对象
dt.getFullYear();//年
dt.getMonth()+1;月
dt.getDate();日
dt.getHours()时
dt.getMinutes()分
dt.getSeconds()秒

2.正则表达式对象的创建
let reg = /^字符数量字符数量字符数量$/
数量可省,省去数量后,默认值为1

let reg = /1.\d{1,2}$/
let falg = reg.test(字符串);
flag值为true或false,表示字符串是否符合正则表达式对象

  1. 伪连接,当按钮用的。示例中当点“退出登陆”后,会触发loginout()方法的执行.
    退出登陆


  1. 012 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值