当前位置:网站首页>nodejs+express+mysql简单博客搭建
nodejs+express+mysql简单博客搭建
2022-07-02 07:01:00 【小猿L】
参考学习视频 参考up视频学习
创建gitee仓库
gitee官网---------新建仓库(右上角+号)-------调好基本信息创建--------回到想要创建文件的位置,右键git bash here------根据gitee上的提示命令进行创建-------看到gitee上创建成功
本地环境搭建
初始化
npm init -y
下载express mysql
npm i express mysql -D
创建app.js并进行基本配置
const express = require("express");
const app = express();
app.get("/login", (req, res) => {
res.send({
status: 0,
message: "请求成功!",
data: [
{ id: 1, name: '张三', age: 23 },
{ id: 2, name: '李四', age: 22 },
{ id: 2, name: '王五', age: 25 },
]
});
res.end();
})
app.listen(3000, () => {
console.log("服务器已开启 http://localhost:3000")
});开启服务
node app.js
查看是否成功配置浏览器输入http://localhost:3000 查看是否有数据
请求成功

路由跳转封装
新建pages目录-----目录下新建index.html login.html给点内容
路由配置app.js通过fs引入html文件(修改和增加app.js为)
const express = require("express");
const app = express();
const fs = require("fs");
app.get("/", (req, res) => {
fs.readFile("pages/index.html", (err, data) => {
if (!err) {
res.end(data);
} else {
console.log(err);
}
})
})
app.get("/toLogin", (req, res) => {
fs.readFile("pages/login.html", (err, data) => {
if (!err) {
res.end(data);
} else {
console.log(err);
}
})
})
app.listen(3000, () => {
console.log("服务器已开启 http://localhost:3000")
});打开localhost:3000默认打开index.html
输入localhost:3000/toLogin默认打开login.html页面
页面路由封装
因为引入文件代码高度重合相似,所以建立util.js文件,将公共的方法放在这里,优化代码
const fs = require("fs");
module.exports = {
read: (url) => {
return new Promise((resolve, rejects) => {
fs.readFile(url, (err, data) => {
if (!err) {
resolve(data);
} else {
console.log(err);
rejects(err);
}
})
})
}
}app.js为:
const express = require("express");
const app = express();
const fs = require("fs");
const util = require("./util");
app.get("/", (req, res) => {
util.read("pages/index.html").then((data) => {
res.end(data);
})
})
app.get("/toLogin", (req, res) => {
util.read("pages/login.html").then((data) => {
res.end(data);
})
})
app.listen(3000, () => {
console.log("服务器已开启 http://localhost:3000")
});访问成功,路由封装成功
连接mysql数据库
配置连接,比如说请求/getList拿到数据库数据,这里出了bug连接不上,最后也是修改了配置
db_config里面属性按照自己的去配置
//数据库操作
app.get("/getList", (err, res) => {
const db_config = {
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "blog"
}
let connect = mysql.createConnection(db_config);
//开始链接数据库
connect.connect(function(er) {
if (er) {
console.log(`mysql连接失败: ${er}!`);
} else {
console.log("mysql连接成功!");
}
});
//基本的查询语句
let sqlQuery = "select * from t_user";
connect.query(sqlQuery, function(e, result) {
if (e) {
console.log(`SQL error: ${e}!`);
} else {
console.log(result);
res.send(JSON.parse(JSON.stringify(result)));
closeMysql(connect);
}
});
//查询成功后关闭mysql
function closeMysql(connect) {
connect.end((err) => {
if (err) {
console.log(`mysql关闭失败:${err}!`);
} else {
console.log('mysql关闭成功!');
}
});
}
});但是每个都需要就太麻烦了,所以我们建立一个db.js专门配置数据库
const mysql = require("mysql");
const db_config = {
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "blog"
}
exports.db = (sql, sqlParams) => {
return new Promise((resolve, reject) => {
let connect = mysql.createConnection(db_config);
//开始链接数据库
connect.connect(function(er) {
if (er) {
console.log(`mysql连接失败: ${er}!`);
} else {
console.log("mysql连接成功!");
}
});
connect.query(sql, sqlParams, function(e, result) {
if (e) {
reject(e)
console.log(`SQL error: ${e}!`);
} else {
console.log(result);
resolve(result)
closeMysql(connect);
}
});
//查询成功后关闭mysql
function closeMysql(connect) {
connect.end((err) => {
if (err) {
console.log(`mysql关闭失败:${err}!`);
} else {
console.log('mysql关闭成功!');
}
});
}
})
}此时的app.js
const express = require("express");
const app = express();
const { db } = require("./db");
const util = require("./util");
app.get("/", (req, res) => {
util.read("pages/index.html").then((data) => {
res.end(data);
})
});
app.get("/toLogin", (req, res) => {
util.read("pages/login.html").then((data) => {
res.end(data);
})
});
//数据库操作
app.get("/getList", (err, res) => {
const sql = "select * from t_user";
const sqlParams = null;
db(sql, sqlParams).then((data) => {
res.send(data);
})
});
// 增加数据库用户操作
//数据库操作
app.get("/addList", (err, res) => {
const sql = "insert into t_user set ?";
const sqlParams = { id: 7, name: 'lld', age: 14, sex: 0 };
db(sql, sqlParams).then((data) => {
res.send(data);
})
});
app.listen(3001, () => {
console.log("服务器已开启 http://localhost:3001")
});静态资源配置
根目录下新建文件 static
static下新建css js upload 目录
css新建index.css文件
配置 在app.js中
app.use('/static', express.static(__dirname + '/static')); //静态文件在index.html中调用
<link rel="stylesheet" href="static/css/index.css">于是便可以看到效果成功引入
数据持久化模块分离
不同路径下的动作可能是一样的,比如说登录或者注册路径都需要向数据库查询手机后操作,所以封装好模块方便你我他。
边栏推荐
- 1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
- 2021-09-12
- Ks009 implement pet management system based on SSH
- Pywin32 opens the specified window
- Pytest learning --base
- webUI自动化学习
- 【Visual Studio】每次打开一个Unity3D的脚本,都会自动重新打开一个新的VS2017
- Flink calculates topn hot list in real time
- MPLS experiment
- Importing tables from sqoop
猜你喜欢

Shutter - canvas custom graph

Application of rxjs operator withlatestfrom in Spartacus UI of SAP e-commerce cloud

KS009基于SSH实现宠物管理系统

Pytest learning --base

Basic usage of mock server

1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
![[pit avoidance guide] pit encountered using ugui: the text component cannot indent the first line by two spaces](/img/6f/e5a30dae824ccb22d1157818be58be.png)
[pit avoidance guide] pit encountered using ugui: the text component cannot indent the first line by two spaces

stm32和电机开发(上位系统)
![[Fantasy 4] the transformation from U3D to UE4](/img/bb/665eba3c8cd774c94fe14f169121da.png)
[Fantasy 4] the transformation from U3D to UE4

STM32 and motor development (upper system)
随机推荐
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
Importing tables from sqoop
【Unity3D】制作进度条——让Image同时具有Filled和Sliced的功能
【教程】如何让VisualStudio的HelpViewer帮助文档独立运行
【MySQL】连接MySQL时出现异常:Connection must be valid and open
两数之和,求目标值
Pytest-- test report allure configuration
axis设备的rtsp setup头中的url不能带参
《MySQL 8 DBA基础教程》简介
[visual studio] every time you open a script of unity3d, a new vs2017 will be automatically reopened
使用Windbg静态分析dump文件(实战经验总结)
sqoop创建job出现的一系列问题解决方法
SQOOP 1.4.6 INSTALL
Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application
Ks009 implement pet management system based on SSH
Database dictionary Navicat automatic generation version
VLAN experiment
判断数组中是否存在重复元素
Rapid prototyping
Blender ocean production