index.js
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World';
}
};
app.use(main);
app.listen(3000, function () {
console.log('server start at 3000');
});
然后 node index.js启动服务
直接访问http://127.0.0.1:3000/test ,会出现Index Page链接,点击之后就会出现hello world
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
};
const main = ctx => {
ctx.response.body = 'Hello World';
};
router.get('/', main);
router.get('/about', about);
app
.use(router.routes()) //吧路由都引入进来
.use(router.allowedMethods());
app.listen(3000, function () {
console.log('server start at 3000');
});
node server.js启动服务