KOA基础

(1)安装KOA 和需要的组件

npm install koa koa-router koa-bodyparser

(2)最基本的语句

// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require(‘koa’);

// 创建一个Koa对象表示web app本身:
const app = new Koa();

// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
await next();
ctx.response.type = ‘text/html’;
ctx.response.body = ‘

Hello, koa2!

’;
});

// 在端口3000监听:
app.listen(3000);
console.log(‘app started at port 3000…’);
(3)处理router

使用koa-router

const Koa = require(‘koa’);

// 注意require(‘koa-router’)返回的是函数:
const router = require(‘koa-router’)();

const app = new Koa();

// log request URL:
app.use(async (ctx, next) => {
console.log(Process ${ctx.request.method} ${ctx.request.url}...);
await next();
});

// add url-route:
router.get(’/hello/:name’, async (ctx, next) => {
var name = ctx.params.name;
ctx.response.body = <h1>Hello, ${name}!</h1>;
});

router.get(’/’, async (ctx, next) => {
ctx.response.body = ‘

Index

’;
});

// add router middleware:
app.use(router.routes());

app.listen(3000);
console.log(‘app started at port 3000…’);

(4)get和post方法

get使用ctx.response.params来获得

post需要经过一个中间件

app.use(bodyParser())

猜你喜欢

转载自blog.csdn.net/weixin_44275692/article/details/89923958
koa