Search code examples
javascriptnode.jsweb-serviceskoaswig-template

"not found" plaintext in browser, when trying to render template with swig on koajs


I am using koajs on node.js and the swig templating engine to learn and code a web service. At the moment the Browser only loads up the words 'not found'. The code worked before i tried to split the program up into multiple files. After then i tried to get it work, even with getting everything back together in one file, without success.

The html file at './templates/base.html' does exist. For clarification, when I run 'node --harmony index.js' there are no errors and I do get the output 'listening on port 3000'. But when I try to load up the page in my browser, i get the plain text 'not found'.

Here are my files:

index.js:

var routes = require('./routes');
var server = require('./server');


routes.baseroute

server.init(3000);

server.js:

var serve = require('koa-static');

var koa = require('koa');

var app = koa();


var init = function(port){

  app.use(serve('./public'));

  app.listen(port);
  console.log('\n   ---> listening on port '+port);
};

exports.init = init;

routes.js:

var koa = require('koa');
var route = require('koa-route');

var views = require('./views');

var app = koa();


var baseroute = app.use(route.get('/', views.baseview));

exports.baseroute = baseroute;

views.js:

var swig = require('swig');

var data = require('./data');


var baseview = function*(){
  var tpl = swig.compileFile('./templates/base.html');
  this.body = tpl(data.basedata);
};

exports.baseview = baseview;

data.js:

var basedata = {user: 'testuser123'};

exports.basedata = basedata;

Solution

  • So what's really happening is after you split them into their own files you created a separate instance of koa in their own file. See:-
    var app = koa();
    in both server.js and routes.js and koa thinks of them as separate apps. It's possible in koa to have more than one apps but you'd have to mount them for them to have any kind of linkage. First, find the main file that you want your linkage to happen. I'm guessing it's server.js and expose other app from their file(route.js). Now when you're linking them just use mount('/', require('./routes')); and koa will link them as one unit. In short:-

    //routes.js
    var koa = require('koa');
    ...
    ...
    var app = koa();
    app.use(route.get('/', views.baseview));
    
    module.exports = app;
    
    //server.js
    var app = require('koa');
    var mount = require('koa-mount');
    var routes = require('./routes');
    ...
    ...
    var init = function(port){
    
      app.use(serve('./public'));
      app.use(mount('/route', routes));
      app.listen(port);
      console.log('\n   ---> listening on port '+port);
    };   
    exports.init = init;