Reputation: 1174
I'm trying to write my first ever koa.js app, and for some reason I just can't set a route with a function. I keep getting a "Not Found" error.
Here's my code -
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
router.get('/', function *(next) {
this.body = "Hello"
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
console.log("Listening on port 3000");
This code is based on the koa-router github example
Then when I go to localhost:3000 I get "Not Found"
What am I missing? Thanks
Upvotes: 4
Views: 5459
Reputation: 75
I know this is old but for anyone who is new in koa, and beside using the new way in koa 3, as i had same error because lot of documents and examples just confuse me, it is said that routes should be last middleare to use but not before settings routes so you should write the line of using routes middlware before the code setter of routes like that:
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
app.use(router.routes())
.use(router.allowedMethods());
router.get('/', function *(next) {
this.body = "Hello"
});
app.listen(3000);
console.log("Listening on port 3000");
Upvotes: 0
Reputation: 9321
I've been getting the same error but i found out that maybe this is the easiest way of doing it.
'strict'
const koa = require('koa')
const app =new koa()
var route = require('koa-router');
const host = 'localhost' || '127.0.0.1';
const port = 3123 || process.env.PORT;
// initiate the route
var my_route = route();
// defines the route
my_route.get('/',function(body, next){
body.body = "I love routes"
});
app.use(my_route.routes())
app.listen(port, host,(err)=>{
if(err){
throw err;
}
console.log("The server has started")
})
Upvotes: 0
Reputation: 305
Now function generator is deprecate in koa2. Used code like
const koa = require('koa'),
router = require('koa-router')();
var app = new koa();
router.get('/', function(ctx, next) {
ctx.body = "Hello"
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
console.log("Listening on port 3000");
Upvotes: 4