技术栈
1.express:Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建
各种 Web 应用,和丰富的 HTTP 工具,使用 Express 可以快速地搭建一个完整功能的网站。
2.mysql:用于操作MySQL数据库
3.body-parser:用于解析JSON请求体
源码
链接:node_admin: NodeJS编写后端接口
具体实现
1.新建文件夹命名为Project,并在文件夹内使用cmd命令初始化node项目
npm init
2.引入相关依赖
npm i express -S
npm i mysql -S
npm i body-parser -S
3.新建utils目录,新建DbUtil,用于连接MySQL的工具类
const mysql = require('mysql');function createConnection() {const connection = mysql.createConnection({host: 'localhost',user: 'root',port: '3306',password: 'admin', // 改成你自己的密码database: 'mumangguo' // 改成你的数据库名称});connection.connect((err) => {if (err) {console.error('Error connecting to database: ' + err.stack);return;}console.log('Connected to database as ID ' + connection.threadId);});return connection;
}module.exports = {createConnection
};
4.在utils目录中继续新建Server.js,用于创建服务器的工具类
const express = require('express');
const bodyParser = require('body-parser'); // 如果使用的是body-parser中间件function startServer() {const app = express();// 监听端口const server = app.listen(8080, '127.0.0.1', function () {const host = server.address().address;const port = server.address().port;console.log("地址为 http://%s:%s", host, port);});// 设置跨域访问app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "*");res.header("Access-Control-Allow-Methods", "*");next();});// 使用 body-parser 中间件来解析 JSON 请求体app.use(bodyParser.json());return app;
}module.exports = startServer;
5.在项目根目录下新建user目录,在user目录中新建UserController.js文件,用于编写处理用户表的相关操作方法
const {createConnection} = require('../utils/DbUtil');
const connection = createConnection();// 登录方法
exports.login = (req, res) => {const {username, password} = req.body;const sql = `SELECT * FROM user WHERE username = '${username}' AND password = '${password}'`;connection.query(sql, (err, result) => {if (err) {res.status(500).json({code: 500, msg: '登录失败'});} else {if (result.length > 0) {res.status(200).json({code: 200, msg: '登录成功'});} else {res.status(500).json({code: 500, msg: '用户名或密码错误'});}}});
};//注册方法
exports.register = (req, res) => {const {username, password} = req.body;const sql = `INSERT INTO user (username, password) VALUES ('${username}', '${password}')`;connection.query(sql, (err, result) => {if (err) {res.status(500).json({code: 500, msg: '注册失败'});} else {res.status(200).json({code: 200, msg: '注册成功'});}});
};
6.在项目根目录下新建main.js入口文件
const startServer = require('./utils/Server');
const {login, register} = require("./user/UserController");const app = startServer();// 处理登录请求
// {"username":"admin","password":"admin"}
app.post('/login', (req, res) => {// 调用UserController的login方法login(req, res);
});// 处理注册请求
// {"username":"admin","password":"admin"}
app.post('/register', (req, res) => {// 调用UserController的register方法register(req, res);
});
7.建立数据库相关表结构
/*Navicat Premium Data TransferSource Server : LocalSource Server Type : MySQLSource Server Version : 80027 (8.0.27)Source Host : 127.0.0.1:3306Source Schema : mumangguoTarget Server Type : MySQLTarget Server Version : 80027 (8.0.27)File Encoding : 65001Date: 12/05/2024 15:12:52
*/
create database mumangguo;
use mumangguo;SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int NOT NULL AUTO_INCREMENT,`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'admin');SET FOREIGN_KEY_CHECKS = 1;
8.在项目根目录中运行main.js文件,启动服务器测试接口即可!
node .\main.js