nodejs中除了express框架, 另外一个非常流行的Node Web服务器框架就是Koa。
事实上,koa是express同一个团队开发的一个新的Web框架:
koa注册的中间件提供了两个参数:
koa通过创建的app对象,注册中间件只能通过use方法:
真实开发中我们如何将路径和method分离呢?
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
if(ctx.request.url === '/login') {
if(ctx.request.method === 'GET') {
ctx.response.body = "Login Success~";
}
} else {
ctx.response.body = "other request~"
}
})
app.listen(8000, () => {
console.log('koa服务器启动成功')
})
koa官方并没有给我们提供路由的库,我们可以选择第三方 库:koa-router
npm install koa-router
const Koa = require('koa');
const userRouter = require('./router/user');
const app = new Koa();
app.use((ctx, next) => {
// ctx.response.body = "hello world";
next()
})
app.use(userRouter.routes());
// 对没有写的请求方法进行拦截
app.use(userRouter.allowedMethods())
app.listen(8000, () => {
console.log('koa路由服务器启动成功')
})
请求地址:http://localhost:8000/users/123
userRouter.get('/:id', (ctx, next) => {
console.log(ctx.request.params.id)
ctx.response.body = "request success"
})
请求地址:http://localhost:8000/login?username=why&password=123
app.use((ctx, next) => {
console.log(ctx.request.query)
ctx.response.body = "Hellp World"
})
请求地址:http://localhost:8000/login
{
"username": "coderhgf",
"password": "123456"
}
安装依赖: npm install koa-bodyparser;
使用 koa-bodyparser的中间件;
const Koa = require('koa');
const bodyParser = require('koa-bodyparser')
const multer = require('koa-multer');
const app = new Koa();
const upload = multer()
app.use(bodyParser());
// 解析任意的form-data传递的数据
app.use(upload.any())
app.use((ctx, next) => {
console.log(ctx.request.body)
console.log(ctx.req.body)
ctx.response.body = "Hello World~"
})
app.listen(8000, () => {
console.log('koa路由服务器启动成功')
})
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const app = new Koa();
const uploadRouter = new Router({prefix: '/upload'})
const upload = multer({
dest: './uploads/'
});
uploadRouter.post('/avatar', upload.single('avatar'), (ctx, next) => {
console.log(ctx.req.file)
ctx.response.body = "上传头像成功";
});
app.use(uploadRouter.routes());
app.listen(8000, () => {
console.log('koa服务器启动成功')
});
输出结果:body将响应主体设置为以下之一:
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
ctx.status = 200
ctx.response.body = {
name: "coderhgf",
age: 20
}
})
app.listen(8000, () => {
console.log('koa服务器启动成功')
})
koa并没有内置部署相关的功能,所以我们需要使用第三方库:
npm install koa-static
部署的过程类似于express:
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
const isLogin = false;
if(!isLogin) {
ctx.app.emit('error', new Error("您还没有登录~"), ctx);
}
})
app.on('error', (err, ctx) => {
ctx.status = 401
ctx.body = err.message
})
app.listen(8000, () => {
console.log('koa服务器启动成功')
})