KOA的基础使用

只是最基础的使用,很多特性都没有用上,准备用来部署vue打包后的dist文件

废话不多说,直接上代码

// 导入koa模块
const Koa = require('koa');
const Router = require('koa-router')
// 创建koa的实例app
const koaBody = require('koa-body');
const koaStatic = require('koa-static');
const path = require('path');
const history = require('koa-connect-history-api-fallback');
const fs = require('fs');

const app = new Koa();
const router = new Router();
app.use(koaStatic(__dirname + '/public'));
app.use(koaBody());
app.use((ctx, next) => {
    
    
  // 在ctx上放入username,后面的所有请求的ctx里都会有username这个变量
  ctx.username = 'Grayly';
  // 处理完之后放行,不使用next()的话,程序会被挂起来不动了
  next();
})
router.get('/about', ctx => {
    
    
  ctx.body = "hello world"
})
router.get('/get', ctx => {
    
    
  ctx.body = ctx.query
})
router.post('/post', async (ctx, next) => {
    
    
  ctx.body = ctx.request.body
  next();
})
app.use(async (ctx, next) => {
    
     // history 中间件
  await next() // 等待请求执行完毕
  if (ctx.response.status === 404) {
    
     //找不到接口时再访问固定文件
    ctx.type = 'text/html; charset=utf-8' // 修改响应类型
    ctx.body = fs.readFileSync(__dirname + '/public/a.txt') // 修改响应体
  }
})
app.use(router.routes());
// app.use(history());
// 监听端口
app.listen(3000, () => {
    
    
  console.log("服务器已启动,http://localhost:3000");
})

Guess you like

Origin blog.csdn.net/chen_daimaxz/article/details/121292976