当前位置:网站首页>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 .
边栏推荐
- 618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
- Operator-1 first acquaintance with operator
- 14.信号量的代码实现
- HDU1228 A + B(map映射)
- Is this code PHP MySQL redundant?
- 《MySQL 8 DBA基础教程》简介
- Hdu1236 ranking (structure Sorting)
- Win11 arm系统配置.net core环境变量
- 1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
- AppGallery Connect场景化开发实战—图片存储分享
猜你喜欢

12.进程同步与信号量

stm32和电机开发(上位系统)

Jsp webshell Free from killing - The Foundation of JSP

JSP webshell free -- the basis of JSP

2022-06-17
![[SUCTF2018]followme](/img/63/9104f9c8bd24937b0fc65053efec96.png)
[SUCTF2018]followme

Operator-1 first acquaintance with operator

"Matching" is true love, a new attitude for young people to make friends

互联网快讯:腾讯会议应用市场正式上线;Soul赴港递交上市申请书

JSP webshell免杀——JSP的基础
随机推荐
JSP webshell免杀——JSP的基础
2.hacking-lab脚本关[详细writeup]
4. Random variables
01-spooldir
正则及常用公式
HDU1234 开门人和关门人(水题)
UVM——Callback
《实习报告》Skywalking分布式链路追踪?
PCL之滤波
1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
618再次霸榜的秘密何在?耐克最新财报给出答案
SUS系统可用性量表
Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application
SQOOP 1.4.6 INSTALL
flume 190 INSTALL
HDU1236 排名(结构体排序)
PCL Eigen介绍及简单使用
Learn open62541 -- [66] UA_ Generation method of string
12.进程同步与信号量
SPSS做Shapiro-Wilk正态分析