Search code examples
node.jskoa2koa-router

Nodejs, koa-router, koa-views (twig) return "Not found"


So I started my new project and a friend of mine conveiced me to ditch PHP and give Nodejs a try with rethinkDB.

I installed everything and without routes, it works. But once I add the routes, I got : Not Found with no error on the console.

Packages:

  "dependencies": {
    "keygrip": "^1.0.1",
    "koa": "^2.3.0",
    "koa-controller": "^1.1.0", //Not used - discontinued ?
    "koa-response-time": "^2.0.0",
    "koa-router": "^7.2.1",
    "koa-views": "^6.0.2",
    "rethinkdbdash": "^2.3.29",
    "socketio": "^1.0.0",
    "twig": "^1.10.5"
  }

server.js:

var Koa = require('koa'),
      Router = require('koa-router'),
      keygrip = require("keygrip"),
      r = require('rethinkdbdash')(),
      views = require('koa-views'),
      Twig = require('twig'),
      twig = Twig.twig,
      app = new Koa(), // Init Koa
      router = new Router(); //Init router

//configure VIEWS
app.use(views(__dirname + '/views/', { extension: 'twig', map: {twig: 'twig' }}))

//Initialize controllers
var ot = require(__dirname+'/controllers/ot.js');

//app.keys = ['im a newer secret', 'i like turtle'];

router
  .get('/', async function (ctx, next) {

      async (ctx, next) => {
        /*ctx.state = {
          session: this.session,
          title: 'app'
        };*/
        ctx.render('index', {
            message: 'Hello world! <3'
        });
      };
  });

app
    .use(router.routes())
    .use(router.allowedMethods());
app.listen(3000);
console.log('server listen on http://localhost:3000');

ot.js:

var ot = function() {};

ot.prototype = {
    'index' : async function(ctx, next) {

        ctx.state = {
            session: this.session,
            title: 'app'
        };

        await ctx.render('index', {
            message: 'Hello world! <3'
        });

        console.log(ctx);

    }
};

module.exports = new ot();

My goal would be to achieve something like:

router.get('/', master.index);
router.post('/search', master.search);
router.get('/ot', ot.index);
router.get('/ot/:id', ot.getById);

Total nodejs noob, I would really appreciate your help :)


Solution

  • so this should work: for the index.js change it to:

    'use strict';
    
    const Koa = require('koa');
    const Router = require('koa-router');
    const keygrip = require("keygrip");
    // const r = require('rethinkdbdash')(); // not needed in this code at the moment
    const views = require('koa-views');
    const Twig = require('twig');
    const twig = Twig.twig;
    
    const app = new Koa(); // Init Koa
    const router = new Router(); //Init router
    
    //configure VIEWS
    app.use(views(__dirname + '/views/', { extension: 'twig', map: {twig: 'twig' }}))
    
    //Initialize controllers
    var ot = require(__dirname+'/controllers/ot.js');
    
    app.keys = ['im a newer secret', 'i like turtle']; // not needed in this code at the moment
    
    router
      .get('/', async function (ctx, next) {
          await ctx.render('index', {
              message: 'Hello world! <3'
          });
      });
    
    // routes from ot.js
    router.get('/ot', ot.index);
    
    app
        .use(router.routes())
        .use(router.allowedMethods());
    app.listen(3000);
    console.log('server listen on http://localhost:3000');
    

    and your controllers/ot.js could then look like this:

    'use strict';
    
    exports.index = async function (ctx, next) {
        await ctx.render('index', {
            message: 'Hello - FROM ot/index'
        });
    };
    
    exports.someOther = async function (ctx, next) {
        // some other function
    };
    

    My sample views/index.twig

    <!DOCTYPE html>
    <html>
        <head>
            <title>My Webpage</title>
        </head>
        <body>
            <h1>My Webpage</h1>
            {{ message }}
        </body>
    </html>
    

    Both routes localhost:3000/ and localhost:3000/ot should work now. The RethinkDB part is missing here because you did not provided any sample code. Hope that helps.