当前位置:网站首页>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 .
边栏推荐
- MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)
- Easyexcel, a concise, fast and memory saving excel processing tool
- Analysis of hot spots in AI technology industry
- From Read and save in bag file Jpg pictures and PCD point cloud
- JSP webshell free -- the basis of JSP
- UVM——Callback
- Sus system availability scale
- (5) Gear control setting of APA scene construction
- [TS] 1368 seconds understand typescript generic tool types!
- [Lua] summary of common knowledge points (including common interview sites)
猜你喜欢
随机推荐
Learn open62541 -- [66] UA_ Generation method of string
Considerations for Apache deploying static web page projects
(5) Gear control setting of APA scene construction
Flutter环境配置保姆级教程,让doctor一绿到底
Ks009 implement pet management system based on SSH
学习open62541 --- [66] UA_String的生成方法
拆解美图SaaS:开着飞机换引擎
MySQL environment configuration
[SUCTF2018]followme
Convert yv12 to rgb565 image conversion, with YUV to RGB test
Redis set password
14.信号量的代码实现
Flink submitter
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
MYSQL环境配置
使用sqlcipher打开加密的sqlite方法
[SUCTF2018]followme
MYSQL关键字
长投学堂上面的账户安全吗?
PCL之滤波
![2. Hacking lab script off [detailed writeup]](/img/f3/29745761cd5ad4df84c78ac904ea51.png)








