当前位置:网站首页>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 .
边栏推荐
猜你喜欢
(5) Gear control setting of APA scene construction
Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application
2.hacking-lab脚本关[详细writeup]
使用Windbg静态分析dump文件(实战经验总结)
Solutions to a series of problems in sqoop job creation
对话吴纲:我为什么笃信“大国品牌”的崛起?
简洁、快速、节约内存的Excel处理工具EasyExcel
14.信号量的代码实现
SPSS做Shapiro-Wilk正态分析
The URL in the RTSP setup header of the axis device cannot take a parameter
随机推荐
Lunix reallocates root and home space memory
Solutions to a series of problems in sqoop job creation
Flink submitter
Kustomize user manual
JSP webshell免殺——JSP的基礎
axis设备的rtsp setup头中的url不能带参
使用Windbg静态分析dump文件(实战经验总结)
Flink calculates topn hot list in real time
Rapid prototyping
Considerations for Apache deploying static web page projects
LabVIEW为什么浮点数会丢失精度
(5) Gear control setting of APA scene construction
Oracle notes
HDU1236 排名(结构体排序)
flume 190 INSTALL
华为联机对战服务玩家掉线重连案例总结
2022-06-17
js promise.all
JSP webshell free -- webshell free
华为游戏初始化init失败,返回错误码907135000