Blog Summary

Web常用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
req.body.xxx //获取页面body里的参数
res.render('xx') //将页面渲染到xx里
req.query.xxx; //获取页面URL中带的参数
res.render('detail',{
blogs: result[0]
}); //渲染页面并传入参数,通过在数据库中查询得到的result是数组,不用result[0]传入,将显示Object对象
<%= blog.content %> //在ejs中接收数据
<% blogs.forEach(blog => { %>
<li>
<a href="/detail?blog_id=<%= blog.id %>"><%= blog.title %></a>
</li>
<% }) %>
</ul> //这种情况是将result直接传入,由于blogs是数组,所以用遍历forEach
//其中a标签中设置了带blog的id跳转
module.exports = {
insertData:insertData,
selectData:selectData,
selectDataContent:selectDataContent
}; //同一个JS中暴露多个函数,
var selectData = require('../tools/db').selectData;
var selectDataContent = require('../tools/db').selectDataContent; //调用暴露的多个函数

Cookie

设置cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var crypto = require('crypto');
var md5 = crypto.createHash('md5');
exports.authorizations = [];
exports.cookies = function(req, res, username){
md5 = crypto.createHash('md5');
md5.update(username + (new Date()).toString());
var auth = md5.digest('hex');
console.log(auth);
exports.authorizations.push({username: username, auth: auth});
res.cookie('username', username, {maxAge: 1 * 30 * 1000});
res.cookie('auth', auth, {maxAge: 1 * 30 * 1000});
}
  • 调用md5.digest生成一组特殊的数值
  • exports.authorizations.push将页面传来的username加入到数组里
  • res.cookie设置username和特殊值存在的时间

将username存入cookie

1
2
3
4
5
6
7
8
9
router.post('/', function(req, res, next) {
var username = req.body.username;
console.log(username);
if(username === ""){
res.render('loginFail');
}
auth.cookies(req, res, username);
res.render('new');
});

设置路由

1
2
3
4
5
6
7
8
9
10
var auth = require('../tools/cookie');
router.get('/new', function(req, res, next) {
if((auth.authorizations.some(e => e.username === req.cookies.username)) && (auth.authorizations.some(e => e.auth === req.cookies.auth))){
console.log(auth.authorizations);
res.render('new');
} else {
res.render("login");
}
});
  • 当客户端发送new请求,进入这个路由
  • 检查req.cookies.username和cookie里存的值是否相同