当前位置:网站首页>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 .
边栏推荐
- C#中索引器
- 14.信号量的代码实现
- "Talking about podcasts" vol.352 the age of children: breaking the inner scroll, what can we do before high school?
- 华为游戏初始化init失败,返回错误码907135000
- Oracle 笔记
- JSP webshell free -- the basis of JSP
- MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)
- nodejs+express+mysql简单博客搭建
- JSP webshell免殺——JSP的基礎
- UWA报告使用小技巧,你get了吗?(第四弹)
猜你喜欢

软件产品管理系统有哪些?12个最佳产品管理工具盘点

Shapiro Wilk normal analysis by SPSS

HDU1236 排名(结构体排序)

LeetCode+ 76 - 80 暴搜专题

Considerations for Apache deploying static web page projects

Use WinDbg to statically analyze dump files (summary of practical experience)

UVM learning - build a simple UVM verification platform

MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)

华为游戏初始化init失败,返回错误码907135000

【AGC】构建服务3-认证服务示例
随机推荐
MongoDB-快速上手MongoDB命令行的一些简单操作
AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
Importing tables from sqoop
【快应用】Win7系统使用华为IDE无法运行和调试项目
AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)
Flutter环境配置保姆级教程,让doctor一绿到底
Considerations for Apache deploying static web page projects
JSP webshell免杀——webshell免杀
Flink submitter
JSP webshell免杀——JSP的基础
Disassembling Meitu SaaS: driving the plane to change the engine
PCL 点云转深度图像
点云投影图片
从.bag文件中读取并保存.jpg图片和.pcd点云
Hdu1236 ranking (structure Sorting)
MySQL数据库远程访问权限设置
Shutter - canvas custom graph
Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application
从MediaRecord录像中读取H264参数