2

I have been struggling to get koa to respond to requests when I use generators. I wrote a test.js app to demonstrate this.

var koa = require('koa');
var app = new koa();
var Router = require('koa-router');
var router = new Router();

router.get('/', function *(next){
    this.body = "hello world";
    console.log("success")
});

app.use(router.routes())
app.use(router.allowedMethods());

app.listen(3000);
console.log("listening on 3000");

I run the server with node v4.6.1

No errors occur, but when I send the get request, I get Not Found and no console log.

This code works though:

var koa = require('koa');
var app = new koa();
var Router = require('koa-router');
var router = new Router();

router.get('/', function (ctx){
    ctx.body = "hello world";
    console.log("success")
});

app.use(router.routes())
app.use(router.allowedMethods());

app.listen(3000);
console.log("listening on 3000");

Any idea why the generators don't run?

2 Answers2

5

If you're using the @next version of koa and koa-router, you should be using async functions for your middleware instead of generator functions which were meant for Koa v1.

Example:

var koa = require('koa');
var app = new koa();
var Router = require('koa-router');
var router = new Router();

router.get('/', async function (ctx){
    // You can use `await` in here
    ctx.body = "hello world";
    console.log("success")
});

app.use(router.routes())
app.use(router.allowedMethods());

app.listen(3000);
console.log("listening on 3000");

Of course, async/await isn't supported right now unless you're using Node v7 and use the --harmony-async-await flag. If you want to use it with Node v4, you will have to use something like babel in order to transpile your code. If you don't want to have a build step for your server-side code, I would recommend just using Koa v1 and stick with generator functions.

Saad
  • 49,729
  • 21
  • 73
  • 112
-1
var koa = require('koa');
var app = new koa();
var router = require('koa-router');   

var route = router();                   // These three lines will help you 
app.use(route.routes());                // to route to your given path and      
route.get("/user/", functionname);      // will call the generator function.

function *functionname(next){
console.log('in side the function');
this.body="hi this is my new page";

yield next;
};
Hamza Amin
  • 11
  • 2
  • While this code snippet may solve the problem, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Cody Gray - on strike Aug 09 '17 at 15:00