KOA的基础使用

本文介绍了如何使用Koa框架结合koa-body、koa-static和koa-router等中间件,部署Vue应用的dist文件。通过设置静态资源路径、处理POST请求和错误页面重定向,实现了一个基础的服务器配置。核心代码展示了如何创建Koa实例,配置路由以及处理HTTP请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

只是最基础的使用,很多特性都没有用上,准备用来部署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");
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值