index.jade没有出现在localhost上

时间:2015-08-11 14:52:58

标签: node.js express pug

我一直在使用node.js,express和jade来构建Web应用程序和数据库     https://cozy.io/en/hack/getting-started/first-app.html
尽管布局相同,我的index.jade没有加载到localhost上。在浏览器终端上没有错误提示原因。我已经检查过我的环境变量是否已设置,并且我已将文件路径更改为index.jade,但它没有任何区别,只是一个白色的屏幕。在我的命令提示符下,服务器正在侦听并且数据库已连接。

My environment folder is   
C:\foodshop and within this I have  
node_modules,   
index.jade,   
package.json,   
shopDB.db,   
simpleserver.js

simpleserver.js包含以下内容 -

// This is the server.
var http = require('http'),
    express = require('express'),
    app = express(),
    sqlite3 = require('sqlite3').verbose(),
    db = new sqlite3.Database('shopDB.db', (function(err) {
        if (!err) {
            console.log("Database is connected ... \n\n");
        } else {
            console.log("Error connecting database, check for shopDB.db file... \n\n");
        }
    }));

/* We add configure directive to tell express to use Jade to                   
   render templates */
app.get('env', (function() {
    app.set('views', __dirname + '');
    app.engine('.html', require('jade').__express);

    // Allows express to get data from POST requests
    app.use(express.bodyParser());
}));

// Database initialization (First list names of tables and check if currently exists.)                                                 
db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='itemList'", function(err, row) {
    if (err !== null) {
        console.log(err);
    } else if (row == null) {
        db.run('CREATE TABLE IF NOT EXISTS  "itemList" ("ID" INTEGER PRIMARY KEY NOT NULL, "itemName" VARCHAR(100) NOT NULL, "itemWeight" INT(5) NOT NULL, "expiryDate" DATE, "itemPrice" double DEFAULT NULL)', function(err) {
            if (err !== null) {
                console.log(err);
            } else {
                console.log("SQL Table 'itemList' initialized.");
            }
        });
    } else {
        console.log("SQL Table 'itemList' already initialized.");
    }
});

// We render the templates with the data                              
app.get('/', function(req, res) {

    db.all('SELECT * FROM itemList ORDER BY itemName', function(err, row) {
        if (err !== null) {
            res.send(500, "An error has occurred -- " + err);
        } else {
            //res.sendfile('./public/index.html')
            res.render('./index.jade', {
                itemList: row
            }, function(err, html) {
                //res.sendfile('./index.jade')
                //res.send(200, html);
                res.status(200).send(html);
            });
        }
    });
});

// We define a new route that will handle item creation                      
app.post('/add', function(req, res) {

    ID = req.body.ID;
    itemName = req.body.itemName;
    itemWeight = req.body.itemWeight;
    expiryDate = req.body.expiryDate;
    itemPrice = req.body.itemPrice;

    sqlRequest = "INSERT INTO 'itemList' (ID, itemName, itemWeight, expiryDate, itemPrice) VALUES('" + ID + "', '" + itemName + "', '" + itemWeight + "', '" + expiryDate + "', '" + itemPrice + "')"
    db.run(sqlRequest, function(err) {
        if (err !== null) {
            res.send(500, "An error has occurred -- " + err);
        } else {
            res.redirect('back');
        }
    });
});

// We define another route that will handle item deletion                     
app.get('/delete/:itemName', function(req, res) {
    db.run("DELETE FROM itemList WHERE itemName='" + req.params.itemName + "'", function(err) {
        if (err !== null) {
            res.send(500, "An error has occurred -- " + err);
        } else {
            res.redirect('back');
        }
    });
});

/* This will allow Cozy to run your app smoothly but
 it won't break other execution environment */
var port = process.env.PORT || 9250;
var host = process.env.HOST || "127.0.0.1";

// Starts the server itself
var server = http.createServer(app).listen(port, host, function() {
    console.log("Server listening to %s:%d within %s environment",
        host, port, app.get('env'));
}); 

这是index.jade文件

doctype 5
html(lang="en")
  head
    title Items

  body


    form(action="add", method="post")
        label ID:
        input(type="text", name="ID")
        label itemName:
        input(type="text", name="itemName")
        label itemWeight:
        input(type='text', name='itemWeight')
        label expiryDate:
        input(type='text', name='expiryDate')
        label itemPrice:
        input(type='text', name='itemPrice')
        input(type="submit", value="Add a new item")

    ul
        - for(item in itemList) {
            li
                a(href=itemList[item].url)= itemList[item].itemName
                |  - (
                a(href="delete/#{itemList[item].id}") delete
                | )
        - }

1 个答案:

答案 0 :(得分:7)

我遵循了相同的教程并进入了他们从Jade模板开始的部分,并且遇到了与您完全相同的问题。我稍微备份了一下,从Jade网站上抓取了示例模板,它运行正常。我更改了Cozy"书签"模板一点点,让它工作。你可以试试这个:

doctype html

不同的doctype在我的例子中有所不同。我不是翡翠的专家,但我一定会尝试,看看你有没有运气。

编辑:再看一下,看起来doctype 5已弃用,现在推荐doctype html

另一个编辑:如果您仍然遇到视图渲染问题,我会做两件事。一,我要检查教程,将你的玉视图与你的相匹配,然后开始一次添加一个东西,直到它中断以缩小问题范围。二,我改变了:

app.get('env', (function() {
    app.set('views', __dirname + '');
    app.engine('.html', require('jade').__express);

    // Allows express to get data from POST requests
    app.use(express.bodyParser());
}));

app.set('views', __dirname + '');
app.engine('.html', require('jade').__express);

// Allows express to get data from POST requests
app.use(express.bodyParser());

你似乎没有使用环境。变量,我没有看到任何理由在其中移动视图渲染器设置。将其移至顶部(如示例中所示),看看它是否适合您。