1、初始化
npm init -y
//package.json
{
//加这一句
"type": "module",
"name": "apiserve",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2、先安装好依赖的包
//express包和mysql数据库包
npm i express@4.17.1 mysql2@2.2.5
3、建立项目启动app.js
// app.js
import express from "express";
//导入路由 import user_router from "./router/user_router"; const app = express();
//使用路由 app.use("/api", user_router); app.listen(3007, () => { console.log("server on http://127.0.0.1"); });
4、建立数据库连接,先创建db这个文件夹
在db文件夹下建立index.js
// db/index.js
import mysql from "mysql2"; const pool = mysql.createPool({ host: "127.0.0.1", port: 3306, database: "my_db_01", user: "admin", password: "root", }); export default pool.promise();
5、建立数据库查询模块,新建文件夹以及相关的js
//user_ctrl.js
import db from "../db/index.js";
export async function getAllUser(req, res) {
try{
const [rows] = await db.query("select id,username,nickname from ev_users");
res.send({
status: 0,
message: "获取用户信息成功",
data: rows,
});
} catch (e){
res.send({
status:1,
message:"获取用户信息失败",
desc:e.message
})
}
}
6、建立路由模块
//user-router.js
import express from "express"; import { getAllUser } from "../controller/user_ctrl.js"; const router = new express.Router; router.get("/user", getAllUser); export default router;
7.返回app.js并运行服务器