简体   繁体   中英

Node: How to fix routing?

I need to use a router to integrate applications. To define an application I use app.use ('/ chat'. The application works separately, but it does not work together with the routing file.

How to fix routing?

/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);

chat/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;

err:

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)

just went through your git repo. You need to include jade in your node modules and in your app. I'll issue a pull request against your repo but the short answer is: update your chat/index.js to the following:

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

You specify an engine via the app.engine() function rather than app.set(). You can then set the view (not views) engine as jade.

complete code: (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);});

(/chat/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;

When using res.render , you have to specify a view engine on root app:

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

More details you could refer this document

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM