简体   繁体   中英

wrong routing with koa-router in koa

I am learning Koa, with basic exercise, but i can´t achieve implement a simple routing, with the code that i got from this page , and this is what i did:

var koa = require('koa');
var router = require('koa-router'); //require it
var app = new koa();
var ro = router();
//and we'll set up 2 routes, for our index and about me pages
ro.get('/hello', getMessage);

function *getMessage() {
    this.body = "Hello world!";
 };
app.use(ro.routes());
app.listen(8008);
console.log('Koa listening on port 8008');

i did´t get any specific error, because the app run with the command node index.js , but i can see any print in the page that i routed.

and i only have 1 file in my folder myproyectoks, and it is index.js, and that's the file that i'm working.

any information that you need pls ask me:D, because i could be forgot something.

The example is out-of-date - Koa middleware is promise-based and generator functions will no longer work directly. The router documentation suggests the following form:

const Koa = require('koa')
const Router = require('@koa/router')

const router = new Router()
router.get(
    '/hello', 
    ctx => ctx.body = 'Hello world!'
)

const app = new Koa()
app.use(router.routes())

app.listen(8008)

To note the other differences, the router module is a class that requires instantiation and the context is passed as an argument to the request handler.

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