当前位置:网站首页>Nodejs+express+mysql simple blog building
Nodejs+express+mysql simple blog building
2022-07-02 10:56:00 【Ape L】
Refer to the learning video Reference resources up Video learning
establish gitee Warehouse
gitee Official website --------- New warehouse ( Upper right corner + Number )------- Adjust the basic information to create -------- Go back to the location where you want to create the file , Right click git bash here------ according to gitee The prompt command on ------- notice gitee Successfully created on
Local environment construction
initialization
npm init -y
download express mysql
npm i express mysql -D
establish app.js And carry out basic configuration
const express = require("express");
const app = express();
app.get("/login", (req, res) => {
res.send({
status: 0,
message: " The request is successful !",
data: [
{ id: 1, name: ' Zhang San ', age: 23 },
{ id: 2, name: ' Li Si ', age: 22 },
{ id: 2, name: ' Wang Wu ', age: 25 },
]
});
res.end();
})
app.listen(3000, () => {
console.log(" Server turned on http://localhost:3000")
});Opening service
node app.js
Check whether the browser input is successfully configured http://localhost:3000 Check for data
The request is successful

Routing jump encapsulation
newly build pages Catalog ----- New under the directory index.html login.html Give me something
Routing configuration app.js adopt fs introduce html file ( Modify and add app.js by )
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(" Server turned on http://localhost:3000")
});open localhost:3000 The default index.html
Input localhost:3000/toLogin The default login.html page
Page route encapsulation
Because the imported file code is highly similar , So build util.js file , Put the public method here , Optimize the code
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 by :
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(" Server turned on http://localhost:3000")
});Successful visit , Route encapsulation succeeded
Connect mysql database
configure connections , For example, request /getList Get the database data , There's something wrong here bug Can't connect , Finally, the configuration is modified
db_config The properties inside are configured according to their own
// Database operation
app.get("/getList", (err, res) => {
const db_config = {
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "blog"
}
let connect = mysql.createConnection(db_config);
// Start linking databases
connect.connect(function(er) {
if (er) {
console.log(`mysql The connection fails : ${er}!`);
} else {
console.log("mysql Successful connection !");
}
});
// Basic query statements
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);
}
});
// Close after successful query mysql
function closeMysql(connect) {
connect.end((err) => {
if (err) {
console.log(`mysql Close the failure :${err}!`);
} else {
console.log('mysql Closed successfully !');
}
});
}
});But it's too troublesome to need everyone , So we build a db.js Special configuration database
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);
// Start linking databases
connect.connect(function(er) {
if (er) {
console.log(`mysql The connection fails : ${er}!`);
} else {
console.log("mysql Successful connection !");
}
});
connect.query(sql, sqlParams, function(e, result) {
if (e) {
reject(e)
console.log(`SQL error: ${e}!`);
} else {
console.log(result);
resolve(result)
closeMysql(connect);
}
});
// Close after successful query mysql
function closeMysql(connect) {
connect.end((err) => {
if (err) {
console.log(`mysql Close the failure :${err}!`);
} else {
console.log('mysql Closed successfully !');
}
});
}
})
}At this time 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);
})
});
// Database operation
app.get("/getList", (err, res) => {
const sql = "select * from t_user";
const sqlParams = null;
db(sql, sqlParams).then((data) => {
res.send(data);
})
});
// Add database user operations
// Database operation
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(" Server turned on http://localhost:3001")
});Static resource allocation
Create a new file in the root directory static
static Under the new css js upload Catalog
css newly build index.css file
To configure stay app.js in
app.use('/static', express.static(__dirname + '/static')); // Static files stay index.html Call in
<link rel="stylesheet" href="static/css/index.css">Then you can see that the effect is successfully introduced
Data persistence module separation
The actions under different paths may be the same , For example, you need to query the database for the mobile phone before logging in or registering the path , So it is convenient for you, me and him to package the module .
边栏推荐
- 1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
- 4.随机变量
- UVM learning - build a simple UVM verification platform
- 1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
- 07 data import sqoop
- Stm32 et développement de moteurs (système supérieur)
- Rapid prototyping
- Jsp webshell Free from killing - The Foundation of JSP
- (五)APA场景搭建之挡位控制设置
- 转换YV12到RGB565图像转换,附YUV转RGB测试
猜你喜欢

Retrofit's callback hell is really vulnerable in kotlin synergy mode!

UVM learning - object attribute of UVM phase

4. Random variables

01 install virtual machine

Rapid prototyping

快应用中实现自定义抽屉组件

From Read and save in bag file Jpg pictures and PCD point cloud

【AppLinking实战案例】通过AppLinking分享应用内图片

Flutter环境配置保姆级教程,让doctor一绿到底
![2. Hacking lab script off [detailed writeup]](/img/f3/29745761cd5ad4df84c78ac904ea51.png)
2. Hacking lab script off [detailed writeup]
随机推荐
Easyexcel, a concise, fast and memory saving excel processing tool
使用华为性能管理服务,按需配置采样率
《MySQL 8 DBA基础教程》简介
4.随机变量
Disassembling Meitu SaaS: driving the plane to change the engine
PCL 从一个点云中提取一个子集
Rapid prototyping
"Matching" is true love, a new attitude for young people to make friends
Flutter——Canvas自定义曲线图
使用sqlcipher打开加密的sqlite方法
Operator-1初识Operator
Analysis of hot spots in AI technology industry
MySQL environment configuration
大华设备播放过程中设置播放速度
全网显示 IP 归属地,是怎么实现的?
flume 190 INSTALL
Transport Optimization abstraction
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
stm32和電機開發(上比特系統)
Hdu1228 a + B (map mapping)