一、新建项目文件夹 myapp 作为项目的文件夹
二、新建index.js作为项目的初始文件
(一)、在index.js文件同级新建一个package.json文件作为项目的配置文件,其中需要配置的基础文件如下:
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"nodemon": "nodemon ./index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"connect-multiparty": "^2.2.0",
"core-js": "^3.2.1",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"jwt-simple": "^0.5.6",
"moment": "^2.24.0",
"mysql": "^2.17.1",
"nodemon": "^1.19.2",
"register-service-worker": "^1.6.2"
}
(二)、index.js文件内主要做引入用,做为文件的入口文件,如下:
const express = require('express')
const app = express()
const path=require('path')
const fs=require('fs')
const cors = require('cors')
app.use(cors())
//注册中间件,拿到res.body的内容
const bodyParser=require("body-parser")
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
// 引入路由
// 使用循环的方式readdir 查询目录 进行路由的注册
fs.readdir(path.join(__dirname,"./router"),(err,filenames)=>{
if(err) return console.log("读取路由失败");
// console.log(filenames);
//循环每一个文件名 循环一次拼接出一个完整的路由模块 然后使用require导入这个路由模块
filenames.forEach(fname=>{
const router=require(path.join(__dirname,'./router',fname))
app.use(router)
})
})
app.listen(3000, () => console.log('http://localhost:3000'))
//这里的app.listen(300,()=>conslole.log(' http://localhost:3000 '))是暴露链接地址 在前端直接引入
前端是用的Vue-cli3.0搭建的项目 在API / server.js里面写接口的 引入如下:
import axios from 'axios'; axios.defaults.baseURL="http://192.168.2.52:3000" axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
(三)、新建router文件分发路由:(在上文index.js中已经介绍了引入router文件导出接口的方法)
const express=require('express')
const router=express.Router()
const ctrl=require("../controller/stu")
// 拿到所有的数据
router.get('/getallclass',ctrl.getallclass)
router.post('/getcom',ctrl.getcom)
router.get('/getmeclsaa',ctrl.getmeclsaa)
router.post('/getmodify',ctrl.getmodify)
router.get('/getagemax',ctrl.getagemax)
router.get('/getclass',ctrl.getclass)
router.get('/getmodstu',ctrl.getmodstu)
module.exports=router
(四)、新建自己的页面写接口和SQL语句 我这里写的是stu 从上面可以看出来 在router中已经引入了stu.js这个文件 而在stu.js里面 则需要我们链接到数据库并且在页面的最下面暴露这个页面写的接口方便router来获取到这个接口
// 引入数据库
const conn=require("../db/sql")
// 写sql语句拿到数据
const getallclass=(req,res)=>{
const headMaster=req.query.headMaster
const monitor=req.query.monitor
const subordinateClass=req.query.subordinateClass
var currentPage=req.query.pageNum;
var size=req.query.pageSize;
// var sql8='select * FROM class where 1=1 '
var sql8=`SELECT m.*,
(SELECT count(id) FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) t) AS total
FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) m where 1=1 `
if(headMaster!=''){
sql8=`SELECT m.*,
(SELECT count(id) FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) t where headMaster='${headMaster}') AS total
FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) m where 1=1 and headMaster='${headMaster}'`
}
if(monitor!=''){
sql8=`SELECT m.*,
(SELECT count(id) FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) t where monitor='${monitor}') AS total
FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) m where 1=1 and monitor='${monitor}'`
}
if(subordinateClass!=''){
sql8=`SELECT m.*,
(SELECT count(id) FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) t where subordinateClass=${subordinateClass}) AS total
FROM (SELECT
com.id,com.competition_type competitionType,com.competition_user competitionUser,com.ranking,com.subordinate_class subordinateClass,
cls.floor,cls.headMaster,cls.monitor,cls.number
FROM
competition com
LEFT JOIN class cls ON com.subordinate_class = cls.className) m where 1=1 and subordinateClass=${subordinateClass} `
}
sql8+=`limit ${(currentPage-1)*size},${size}`
conn.query(sql8,(err,result)=>{
if(err) return res.send({starus:400,message:"查询失败"})
res.send({status:200,message:'请求成功',data:result})
})
}
//新增学生参加比赛信息
const getcom=(req,res)=>{
const body=req.body
var sql81=`insert into competition(competition_type,competition_user,ranking,subordinate_class) values(${body.competition_type},'${body.competition_user}',${body.ranking},${body.subordinate_class})`
conn.query(sql81,(err,result)=>{
if(err) return res.send({starus:401,message:'新增失败'})
res.send({status:200,message:'新增成功',data:result})
})
}
//选择班级后获取到对应的班级信息
const getmeclsaa=(req,res)=>{
const subordinateClass=req.query.subordinateClass
var sql12=`SELECT * FROM class WHERE className=${subordinateClass}`
conn.query(sql12,(err,result)=>{
if(err) return res.send({starus:400,message:"查询失败"})
res.send({status:200,message:'请求成功',data:result})
})
}
//修改比赛信息
const getmodify=(req,res)=>{
const body=req.body
var sql82=`UPDATE competition SET competition_user='${body.competition_user}', ranking=${body.ranking},competition_type=${body.competition_type},subordinate_class=${body.subordinate_class} WHERE id=${body.id}`
console.log(sql82);
conn.query(sql82,(err,result)=>{
if(err) return res.send({starus:401,message:'修改失败'})
res.send({status:200,message:'修改成功',data:result})
})
}
//查询年龄在十八岁以上的
const getagemax=(req,res)=>{
var age=req.query.age;
const sql1=`SELECT * from stuclass WHERE age>${age}`
conn.query(sql1,(err,result)=>{
if(age=='') return res.send({starus:200,message:'null'})
if(err) return res.send({starus:401,message:'查询失败'})
res.send({status:200,message:'请求成功',data:result})
})
}
//查询学生所在班级
const getclass=(req,res)=>{
const sql2=`SELECT * from (SELECT s.*,c.name as className FROM stuclass s LEFT JOIN class c ON s.cid = c.id) t WHERE t.className='一(1)'`
conn.query(sql2,(err,result)=>{
if(err) return res.send({starus:403,message:'查询失败'})
res.send({code:200,message:'请求成功',data:result})
})
}
//修改学生年龄
const getmodstu=(req,res)=>{
const num=req.query.num
const ageChang=req.query.ageChang
const sql3=`UPDATE stuclass SET age = ${ageChang} WHERE age < ${num}`
conn.query(sql3,(err,result)=>{
if(err) return res.send({starus:403,message:'查询失败'})
res.send({code:200,message:'请求成功',data:result})
})
}
module.exports={
getallclass,
getcom,
getmodify,
getmeclsaa,
getagemax,
getclass,
getmodstu
}
(五)、最后我们来看一下引入数据库是如何操作的
const mysql=require("mysql");
const conn=mysql.createConnection({
host:"localhost", //这里是链接数据库 我的是本地启动的 所以是localhost
user:"root", //输入mysql用户名
password:"root", //输入mysql密码
database:"new_text" //这里是输入的库名
})
module.exports=conn
三、以上就是node.js express框架写接口的大概流程 源码都贴出来了,应该很好理解
我这里是自己写的前后端项目 试着写的node.js 肯定还有不到位的地方