...
res.json(responseData);
return;
}
// 给数据库中添加该条信息
var user = new User({ username:username,password:password });
return user.save(); // 返回promise对象
}).then(function( newUserInfo ){
console.log(newUserInfo);
res.json(responseData); // 数据保存成功
});
});
cookies 模块的使用
全局(app.js)注册使用
// 设置cookie
// 只要客户端发送请求就会通过这个中间件
app.use((req, res, next) => {
req.cookies = new cookies(req, res); /**
* 解析用户的cookies信息
* 查询数据库判断是否为管理员 isAdmin
* 注意:查询数据库是异步操作,next应该放在回调里边
*/
req.userInfo = {};
if (req.cookies.get("userInfo")) {
try {
req.userInfo = JSON.parse(req.cookies.get("userInfo"));
// 查询数据库判断是否为管理员
User.findById(req.userInfo._id).then(function (result) {
req.userInfo.isAdmin = Boolean(result.isAdmin);
next();
});
} catch (e) {
next();
}
} else {
next();
}
});
// 当用户登录或注册成功之后,可以为其设置cookies
req.cookies.set("userInfo",JSON.stringify({
_id:result._id,
username:result.username
}));
swig模板引擎
1.变量
{{ name }}
2.属性
{{ student.name }}
3.if判断
{ % if name === ‘郭靖’ % }
hello 靖哥哥
{ % endif % }
4.for循环
// arr = [1, 2, 3]
{ % for key, val in arr % }
<p>{ { key } } — { { val } }</p>
{ % endfor % }
5.set命令
用来设置一个变量,在当前上下文中复用
{% set foo = [0, 1, 2, 3, 4, 5] %}
{% extends ‘layout.html’ %} // 继承某一个HTML模板
{% include ‘page.html’ %} // 包含一个模板到当前位置
{% block main %} xxx {% endblock %} //重写某一区块
6.autoescape 自动编码
当想在某个div中显示后端生成的HTML代码,模板渲染时会自动编码,
以字符串的形式显示。通过以下方式,可以避免这个情况:
<div id="article-content" class="content">
{% autoescape false %}
{{ data.article_content_html }}
{% endautoescape %}
</div>用户管理和分页
CRUD用户数据
const User = require('../models/user');// 查询所有的用户数据
User.find().then(function(users){
});
// 根据某一字段查询数据









