节点:如何修复路由?

时间:2017-06-08 13:54:23

标签: javascript node.js express routing nodes

我需要使用路由器来集成应用程序。要定义应用程序,我使用app.use(' / chat'。应用程序单独工作,但它不能与路由文件一起使用。

如何修复路由?

/app.js

let express = require('express'),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./chat/history.db');
    var routes = require('./chat');
    app.use('/chat', routes);
http.listen(3000);

聊天/ index.js

let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");


// VIEWS SETTINGS
app.set('views', __dirname + '/tpl');
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
app.use(express.static(__dirname + '/tpl'));


// ROUTER
router.get("/", function (req, res) {
    res.render('page', {"name": "Виталий"})
});


// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}


// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;

错误:

Error: No default engine was specified and no extension was provided.
    at new View (C:\chat2\chat2\node_modules\express\lib\view.js:62:11)
    at Function.render (C:\chat2\chat2\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\chat2\chat2\node_modules\express\lib\response.js:971:7)
    at C:\chat2\chat2\chat\index.js:41:9
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\chat2\chat2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\chat2\chat2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at C:\chat2\chat2\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\chat2\chat2\node_modules\express\lib\router\index.js:335:12)

2 个答案:

答案 0 :(得分:1)

刚刚通过你的git repo。您需要在节点模块和应用程序中包含jade。我会针对您的回购发出拉取请求,但简短的回答是:将您的chat / index.js更新为以下内容:

app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');

您可以通过app.engine()函数而不是app.set()指定引擎。然后,您可以将视图(而不是视图)引擎设置为jade。

完整代码:(index.js)

let express = require('express'),
    app = express(),
    http = require('http').Server(app),
    cfenv = require('cfenv'),
    appEnv = cfenv.getAppEnv();;

    app.set('appName', 'chat');
    app.set('port', appEnv.port);
    app.use('/', require("./chat/index"));

    var server = app.listen(app.get('port'), function() {console.log(app.get('appName')+' is Listening on port %d', server.address().port);});

(/聊天/ index.js)

let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");


// VIEWS SETTINGS
console.log("__dirname is: "+__dirname);

app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
//app.use(express.static(__dirname + '/tpl'));


// ROUTER
router.get("/", function (req, res) {
    try{
        res.render('page');
    } catch(err){
        console.log(err)
    }


});


// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}


// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;

答案 1 :(得分:0)

使用res.render时,您必须在root app上指定一个视图引擎:

app.set('view engine', 'jade')

您可以参考this document

了解更多细节