零基础搭建Node.js、Express、Ejs、Mongodb服务器及应(5)


exports.userlist = function(db) {
    return function(req, res) {
        var collection = db.get('usercollection');
        collection.find({},{},function(e,docs){
            res.render('userlist', {
                "userlist" : docs
            });
        });
    };
};


好吧,事情变得有点复杂了。这里首先定义了一个function,接收我们传过来的db变量,然后调用一个跟前面两个route一样的page render。我们告诉它需要读取usercollection,做一个查找,返回的数据保存在docs变量中。一旦我们读取到了内容,就调用render来渲染userlist模板页面,把获取到的docs变量作为模板引擎中的userlist变量传递进去。

接下来建立我们的Ejs模板。在views目录下打开index.ejs,另存为userlist.ejs,然后把它的HTML修改成这样:

复制代码 代码如下:


<!DOCTYPE html>
<html>
<head>
<title>USERLIST</title>
<link href='https://www.jb51.net/stylesheets/style.css' />
</head>
<body>
<h1>Userlist</h1>
<ul>
<%
for(var i in userlist){
%>
<li><a href=https://www.jb51.net/”mailto:<%=userlist[i].email%>”><%=userlist[i].username%></a></li>
<% } %>
</ul>
</body>
</html>


保存文件,重启node服务器。希望你还记得怎么重启。打开浏览器,访问:3000/userlist,你应该能看到这样的界面:

零基础搭建Node.js、Express、Ejs、Mongodb服务器及应

点提交按钮,你会看到一个“can't post to /adduser”的错误。我们来修正它。

第2步 – 创建你的数据库处理函数

跟以前一样,我们修改app.js,然后是route文件,然后是ejs模板。不过,这里不需要ejs模板,因为我们post以后会跳转。在app.js的app.get()这一段的后面添加一行:

复制代码 代码如下:


app.post('/adduser', routes.adduser(db));


注意这里是app.post,不是app.get了。来设置route吧。回到routes/index.js,创建我们的数据库插入函数。这个比较大,所以我建议你写好注释。

复制代码 代码如下:


exports.adduser = function(db) {
    return function(req, res) {

// Get our form values. These rely on the "name" attributes
        var userName = req.body.username;
        var userEmail = req.body.useremail;

// Set our collection
        var collection = db.get('usercollection');

// Submit to the DB
        collection.insert({
            "username" : userName,
            "email" : userEmail
        }, function (err, doc) {
            if (err) {
                // If it failed, return error
                res.send("There was a problem adding the information to the database.");
            }
            else {
                // If it worked, set the header so the address bar doesn't still say /adduser
                res.location("userlist");
                // And forward to success page
                res.redirect("userlist");
            }
        });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxxyz.html