Skip to content

Commit

Permalink
完成README
Browse files Browse the repository at this point in the history
  • Loading branch information
peng committed Nov 24, 2016
1 parent 4110d8a commit b7d889d
Show file tree
Hide file tree
Showing 11 changed files with 229 additions and 10 deletions.
3 changes: 3 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion .idea/server.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

221 changes: 220 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# 使用node.js + express开发简易后台
> 开发环境node.js + express
## 项目预览
![](./public/images/express.gif)
## 将项目克隆到本地
git clone https://github.com/peng1992/express.git
## 安装项目依赖
Expand Down Expand Up @@ -31,5 +32,223 @@
* app.js --------------------------存放的Express项目中最基本的配置信息
* package.json --------------------项目依赖文件

## 文件解析
### app.js
// 引入资源文件
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index'); ---------------------------引入index.js路由配置文件
var data = require('./routes/data'); ---------------------------引入data.js路由配置文件

var app = express(); -------------------------------------------用express创建一个app应用

// 视图引擎设置
app.set('views', path.join(__dirname, 'views')); ---------------指定视图文件夹 views/
app.set('view engine', 'ejs'); -----------------------------------指定视图引擎 ejs

// 使用刚刚加载的资源
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); --------------------------------------- 使用cookie
app.use(express.static(path.join(__dirname, 'public'))); -----------指定公共资源文件夹 为public/

app.use('/', index); ----------------------------当路径为'/',即'http://localhost:3000/'时,匹配index.js
app.use('/data', data); ------------------------当路径为'/data',即'http://localhost:3000/data'时,匹配data.js
// 匹配404,即路径未匹配时
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// 当路径匹配错误时
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

### index.js页面定义的接口如下:(全部为get请求)
* / -----------------------首页
* /edit?type=it -----------------------------互联网
* /edit?type=cookies ---------------------笑料
* /edit?type=manager --------------------管理
* /edit?type=sanwen ----------------------散文
* /tuijian -------------------------------------推荐

#### index.js是怎样定义这些接口呢?
router.get('/edit', function(req, res, next) {...}
以'/edit'为url的ajax请求,就会执行上面的回调函数,让我们来看一下回调函数里面都写了些什么?

router.get('/edit', function(req, res, next) {
if(!req.cookies.user){ ---------------------------判断用户是否已登录
return res.render('login',{});
}
var type = req.query.type; ----------------------获取查询参数type的值
if(type){ ---------------------------如果查询参数存在
var obj = {};
switch(type){ ---------------------------------根据不同的type,返回不同的值
case 'sanwen':
obj = {};
break;
case 'it':
obj = {};
break;
case 'manager':
obj = {};
break;
case 'cookies':
obj = {};
break;
default :
return res.send({
status:0,
info:'参数错误'
});
break;
}
fs.readFile(PATH + type + '.json', (err, data) => { ------------------------------ 读取文件,并执行回调函数 if (err) {
if (err) { ---------------------------------如果读取失败
return res.send({
status:0, ---------------------------------返回错误状态码0
info: 'fail.....'
});
}

var obj = JSON.parse(data.toString());
return res.render('edit', { ----------否则,如果读取成功,渲染模板edit.jsp,返回数据obj
data: obj
});
});
}else { -------------------------------------------如果查询参数不存在
return res.send({
status:0,
info: '参数错误'
});
}
});

#### 打开[http://localhost:3000/edit?type=it](http://localhost:3000/edit?type=it),会提示需要登录,![](./public/images/login.png)用户登录接口[/login](http://localhost:3000/login),在data.js中设置,账号admin密码12345,登录成功后,会出现如下界面
![](./public/images/it.png)
### data.js定义的接口
* 读数据接口---get请求
+ /write?type=it ------------------------------------读取it.json中的数据
+ /write?type=cookies
+ /write?type=manager
+ /write?type=sanwen
+ /write?type=tuijian

* 写入数据接口----post请求
+ /write?type=it ------------------------------------向it.json写入数据
+ /write?type=cookies
+ /write?type=manager
+ /write?type=sanwen
+ /write?type=tuijian

* 阅读模块写入数据接口----post请求
+ /write_config

* 登录接口----post请求
+ /login

#### 以写入数据接口为例,'/write?type=it'会执行下面的代码

router.post('/write',function(req, res, next){
if(!req.cookies.user){ ------------------------判断是否已登录
return res.render('login',{});
}
// 文件名
var type = req.param('type') || ""; -------------------------获取请求参数type的值
// 关键字段
var url = req.param('url') || ''; -------------------------获取请求参数url的值
var title = req.param('title') || ''; ---------------------获取请求参数title的值 var img = req.param('img') || '';
if(!type || !url || !title || !img){ ---------------------如果这些请求参数有一个不存在
return res.send({
status:0,
info:'提交的字段不全'
});
}
//1)读取文件
var filePath = PATH + type + '.json'; --------------------否则,会读取对应的json文件
fs.readFile(filePath, function(err, data){
if(err){ --------------------------如果读取数据失败
return res.send({ --------------返回错误状态信息
status:0,
info: '读取数据失败'
});
}
------------------------如果读取数据成功,则继续执行
var arr = JSON.parse(data.toString()); ----------------------将json文件中的数据取出来,以便待会写入
//代表每一条记录
var obj = { ----------------------待写入的数据
img: img,
url: url,
title: title,
id: guidGenerate(), ---------------------数据的id
time: new Date() ---------------------时间戳
};
arr.splice(0, 0, obj); ------------------------在arr数组中插入数据
//2)写入文件
var newData = JSON.stringify(arr);
fs.writeFile(filePath, newData, function(err){ -------------------------将newData写入filePath对应的文件
if(err){ -----------------如果写入文件失败
return res.send({ --------------------返回错误状态信息
status:0,
info: '写入文件失败'
});
}
return res.send({ ------------------------如果成功,返回正确状态信息
status:1,
info: obj
});
});
});
});
#### 测试一下,这个接口是否正确
$.ajax({
type: 'POST',
url: '/data/write',
data: {
type: 'it',
title: '测试标题',
url: 'www.xxx.com',
img: 'www.xxx.com/images/xxx.png'
},
success: function(data){
if(data.status){
alert('添加数据成功');
}else{
alert('添加失败');
}
},
error: function(){
alert('添加失败');
},
dataType: 'json'
});
#### 打开public/data/it.json,会发现多了一条数据,说明数据输入接口是ok的
##### it.json
[
{
"img": "www.xxx.com",
"url": "www.xxx.com/images/xxx.png",
"title": "测试标题",
"id": "25478B43-C814-4499-9AF5-2BB010F98099",
"time": "2016-11-24T14:17:23.659Z"
}
]

## 至此,一个简单的后台接口就完成了
2 changes: 0 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ var bodyParser = require('body-parser');

var index = require('./routes/index');
var data = require('./routes/data');
var users = require('./routes/users');

var app = express();

Expand All @@ -24,7 +23,6 @@ app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/data', data);

// catch 404 and forward to error handler
Expand Down
2 changes: 1 addition & 1 deletion public/data/cookies.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[{"img":"1234","url":"1234","id":"3C596665-910C-4741-852E-23A611EE6B78","time":"2016-11-22T12:44:03.140Z"},{"img":"1234","url":"1234","id":"EFFCE0F3-19BB-4ADA-962D-7C51ABEBD3D6","time":"2016-11-22T12:43:59.588Z"},{"img":"xxxx.png","url":"http://www.mamicode.com/info-detail-1086071.html","id":"561230D6-D045-4559-9C17-3CB59C8F770A","time":"2016-11-16T15:45:37.067Z"}]
[{"img":"sadf","url":"sadfqwe","title":"123","id":"4C5709DB-FCA4-429F-8F24-0C71EE5FE4B2","time":"2016-11-24T14:23:22.086Z"},{"img":"1234","url":"1234","id":"3C596665-910C-4741-852E-23A611EE6B78","time":"2016-11-22T12:44:03.140Z"},{"img":"1234","url":"1234","id":"EFFCE0F3-19BB-4ADA-962D-7C51ABEBD3D6","time":"2016-11-22T12:43:59.588Z"},{"img":"xxxx.png","url":"http://www.mamicode.com/info-detail-1086071.html","id":"561230D6-D045-4559-9C17-3CB59C8F770A","time":"2016-11-16T15:45:37.067Z"}]
2 changes: 1 addition & 1 deletion public/data/it.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[{"img":"1234","url":"1234","id":"6D273A69-2E04-4409-ADD6-A03E7A55FE91","time":"2016-11-22T12:43:47.091Z"},{"img":"1234","url":"134","id":"1965836E-306D-460A-BF53-1E59B89C23D6","time":"2016-11-22T12:43:43.954Z"},{"img":"1234","url":"1234","id":"85EADDFA-3873-4671-BDA8-5D262A43C505","time":"2016-11-22T12:43:40.525Z"},{"img":"2","url":"3","id":"056AFB70-C394-4392-A424-3968AD090735","time":"2016-11-22T12:32:36.090Z"},{"img":"1","url":"1","id":"8519B09D-F8AC-4C37-9AFA-F4375E4BDD90","time":"2016-11-22T12:26:59.831Z"},{"img":"xxx.ong","url":"www.xxx.com","id":"E7DC9AC8-953C-471D-8C7E-8A29C79E18B9","time":"2016-11-16T13:32:15.968Z"},{"title":"咋咋逆袭","url":"www.xxx.com","img":"xxx.png"}]
[{"img":"1234","url":"1234","title":"1234","id":"920721E3-80FE-4E2E-961C-DA1C384E00FB","time":"2016-11-24T14:23:07.533Z"},{"img":"www.xxx.com","url":"www.xxx.com/images/xxx.png","title":"测试标题","id":"25478B43-C814-4499-9AF5-2BB010F98099","time":"2016-11-24T14:17:23.659Z"}]
Binary file added public/images/express.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/it.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/login.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 1 addition & 3 deletions routes/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,7 @@ router.post('/login', function(req, res, next){
//密码加密 md5(md5(password + '随机字符串'))
//密码需要加密-> 可以写入JSON文件
if(username === 'admin' && password === '123456'){
req.session.user = {
username: username
};
res.cookie('user',username);
return res.send({
status: 1
});
Expand Down
1 change: 0 additions & 1 deletion views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
<div class="panel_item">
<a style="background-color:#D94C59;" href="/tuijian">模块配置</a>
</div>
>>>>>>> origin/master
</div>
</body>
</html>

0 comments on commit b7d889d

Please sign in to comment.