1. Create a project
1.1 Create a mycms project
To generate the pageage.json file, we use npm init -y
When writing a nodejs project, if you only write interfaces and do not need to write pages, you can just give the interface document and interface address to the front-end developer. Next, the front-end developer reads your interface document and retrieves data to display in the view layer.
The mycms project we are writing now has front-end data retrieval and background data retrieval.
1.2 Create project directory
common public js module directory (paging, file upload)
config file configuration directory
db.js (nodejs connection data)
images image resource directory
public public resource directory
admin background resource directory
images
css
js
fonts
home front desk resource directory
images
css
js
fonts
routers routing configuration file
home.js
admin.js
admin background routing configuration file
Because there are many functional modules in the background, each functional module corresponds to a js file
For example: the routing configuration file of the background management function module admin.js
upload file upload directory
The background operation for uploading resources such as images is the directory where they are stored.
images public image directory
views frontend and background template file directory
home frontend template file directory
admin background template file directory
admin The template file directory corresponding to the background administrator function module
add.html Add administrator page
edit.html Edit administrator page
index.html Administrator list page
app.js project entry file
1.3 Project entry file configuration and start the project
app.js project entry file
Our nodejs project uses express framework.
The official Chinese website address of the express framework:Express - a web application development framework based on the Node.js platform - Express Chinese Documentation | Express Chinese Website
All corresponding API interfaces provided by this framework can be checked on this official website.
Steps:
-
To introduce the express framework, you must first download it
Use npm to download and install
npm install express --save
2. app.js simple routing configuration
// 导入express框架
let express = require('express');
// 初始化express
let app = express();
app.get('/',function(req,res){
res.send('hi nidejs');
})
// 监听服务器
let port = 3000;
app.listen(port,()=>{
console.log('node服务器已经启动,端口是:'+port);
})
3. Install node automatic restart tool
nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in a directory are detected.
Function: Automatically restart the node server
Enter in the command window
npm install nodemon --save
Note: Local installation requires specifying the command to be executed in the script script of the package.json
file
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"server":"nodemon ./server.js"
},
Start the nodejs server and start the command in the terminal:
npm run server
In the command window, you can see nodemon starting to work:
4. Configure front-end module routing and back-end module routing
routers---home.js
// 导入express框架
let express = require('express');
// 实例化路由对象
let router = express.Router();
// 前台首页页面路由
router.get('/', function(req,res,next){
res.send('我要访问前台首页页面')
})
module.exports = router;
routers---admin.js
// 导入express框架
let express = require('express');
// 实例化路由对象
let router = express.Router();
// 后台登录页面路由
router.get('/login', function(req,res,next){
res.send('我要访问登录页面')
})
module.exports = router;
Next, we go to the app.js file to set up. We need to be able to access and read the above two routing module files.
// 导入前台路由和后台路由
let adminRouter = require('./routers/admin.js');
let homeRouter = require('./routers/home.js');
// 使用前台路由
// 参数1:匹配路由规则
// 参数2:请求路由规则
app.use('/',homeRouter);
app.use('/admin',adminRouter);
Complete code:
// 导入express框架
let express = require('express');
// 初始化express
let app = express();
app.get('/',function(req,res){
res.send('hi nidejs!!!!!');
})
// 导入前台路由和后台路由
let adminRouter = require('./routers/admin.js');
let homeRouter = require('./routers/home.js');
// 使用前台路由
// 参数1:匹配路由规则
// 参数2:请求路由规则
app.use('/',homeRouter);
app.use('/admin',adminRouter);
// 监听服务器
let port = 3000;
app.listen(port,()=>{
console.log('node服务器已经启动,端口是:'+port);
})
test:
5. We configure the directories involved in the project in the app
Set static resource access directory
// 设置静态资源的访问
app.use('/public', express.static(__dirname+'/public'));
app.use('/upload', express.static(__dirname+'/upload'));
app.use('/images', express.static(__dirname+'/images'));
test:
Place a 1.png in the public directory. Place a 1.png in the upload directory. Place a 3.jpg in the images directory.
In the address of the browser, we visit:
Preview:
6. Load the template file and configure the template engine
Download and install ejs
npm install ejs --save
In the app.js entry file, the configuration is as follows:
// 设置模板的存放目录
// 第一个参数:固定的
// 第二个参数:模板存在的目录
app.set('views','./views');
// 定义使用的模板引擎
// 第一个参数:模板引擎的名称,模板引擎的后缀
// 第二个参数:使用模板引擎的方法
app.engine('html',ejs.__express)
Special note: './views' should be written with .dot, but do not write this .dot. The template file cannot be accessed.
Then, go to routers---home.js, find the front page page route, and load the page
// 前台首页页面路由
router.get('/home', function(req,res,next){
// res.send('我要访问前台首页页面')
// 载入页面
res.render('home/index.html')
})
test:
1.4 Load the foreground and background pages
1.4.1 Load the front page
Steps:
(1) Open the template file you prepared in advance. Copy the source code in the template file to views--home-index.html.
(2) Then adjust the paths of css, js, and images.
Put the front-end resource file in the template file as follows:
Just copy it to the public---home directory.
(3) In the file views--home-index.html, adjust the path as follows:
The operation of other front-end pages is the same as above.
1.4.2 Load the background page
Steps:
(1) Open the template file you prepared in advance. Copy the source code in the template file to views--admin-login.html.
(2) Then adjust the paths of css, js, and images.
Put the front-end resource file in the template file as follows:
Just copy it to the public---home directory.
(3) In the file views--home-index.html, adjust the path as follows:
2. Development of backend administrator functions
In the left area of the views---admin---index.html file, set the menu items:
<h2><span class="icon-pencil-square-o"></span>管理员管理</h2>
<ul style="display:block">
<li><a href="" target="right"><span class="icon-caret-right"></span>管理员列表</a></li>
<li><a href="" target="right"><span class="icon-caret-right"></span>添加管理员</a></li>
<li><a href="" target="right"><span class="icon-caret-right"></span>编辑管理员</a></li>
</ul>
Then configure the routes and pages corresponding to these three functions.
2.1 Nodejs connects to database
Steps:
(1) Download the mysql database module
npm install mysql --save
(2) Configure connection
config---db.js:
//下载mysql数据库模块--npm install mysql
// 导入数据库
const mysql=require('mysql');
//设置数据库连接属性
let connect=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'mycms'
})
//开始连接数据库
connect.connect()
//抛出
module.exports=connect;
2.2 Administrator list
Go to the background administrator module file routers---admin---admin.js and set:
router.get('/list',function(req,res,next){
// res.send('访问登录页面')
//执行sql语句
let sql='select * from admin';
//从数据库中查询数据
mysql.query(sql,function(err,data){
if(err){
return false;
}else{
data.forEach(function(item){
item.addtime=moment(item.addtime).format("YYYY-MM-DD HH:mm:ss")
console.log(data);
})
//载入页面
res.render('admin/admin/list.html',{data:data})
}
})
})
Print data output:
To format the time retrieved from the database, we need to use the moment module.
Download and install moment
npm install moment --save
Get a timestamp and test online:
Online timestamp, Unix timestamp, timestamp conversion - online tool
1659167151445 Add this timestamp to the database field.
set up:
data.forEach(item=>{
item.addtime = moment(item.addtime).format("YYYY-MM-DD HH:mm:ss");
});
Then, in the corresponding template file, render the output data:
<!-- ejs模板引擎 -->
<% data.forEach((item)=>{ %>
<tr>
<td style="text-align:left; padding-left:20px;"><input type="checkbox" name="id[]" value="" />
<%= item.id %>
</td>
<td><%= item.name %> </td>
<td><%= item.addtime %> </td>
<td><div class="button-group">
<a class="button border-main" href="add.html">
<span class="icon-edit"></span> 修改</a>
<a class="button border-red" href="javascript:void(0)" onclick="return del(1,1,1)">
<span class="icon-trash-o"></span> 删除</a>
</div>
</td>
</tr>
<% }) %>
Preview:
2.3 Add administrator
Download layui, where the date needs to use laydate.js
http://layui.winxapp.cn/doc/modules/laydate.html
http://layui.winxapp.cn/laydate/index.html
Add time, use laydate here, see the official website for settings
The settings are as follows:
Copy this code from the official website
laydate.render({
elem: '#addtime'
,type: 'datetime'
});
Copy into our template add.html file and use:
Preview:
We go to the app.js entry file, download and install body-parser,
npm install body-parser --save
and configure:
// 处理post请求
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
After this is configured, the data submitted by our post can be received by the interface.
Preview:
Add timestamp to database table:
List of page administrators: