创建服务器koa实例
const Koa = require('koa')
const app = new Koa
ctx.body = {} //对象中写响应前端的数据
app.listen(3000) //监听端口号
创建路由router实例
const router = require('koa-router')()
router.get('/路由', async ctx => {
await ctx.render('响应准备渲染的文件夹中渲染index.html的文件')
})
router.post('/路由', async ctx => {
})
router.post('/koa/:id',async ctx => {
console.log(ctx.params)
})
app
.use(router.routes())
.use(router.allowedMethods())
.listen(3000)
koa-body模块(处理 post 请求)
const koaBody = require('koa-body')
app.use(koaBody())
let opt = {
multipart: true,
strict:false,
encoding: "gzip",
formidable: {
uploadDir: resolve(__dirname, "uploadDir"),
maxFileSize: 1024 * 500,
keepExtensions: true,
onFileBegin(name,file){
}
}
}
router.post('/update',
async (ctx, next) => {
try {
await next()
}catch{}
},
koaBody(opt),
async ctx => {
ctx.body = "{data}"
})
@koa/cors模块(解决跨域问题)
const cors = require('@koa/cors')
app.use(cors())
koa-views模块(响应解析的html等超文本)
const views = require('koa-views')
app.use(views('准备渲染的静态文件夹路径'), {
extension: "文件夹中文件的后缀名"
})
koa-static模块(访问静态链接自动响应)
const koaStatic = require('koa-static')
app.use(koaStatic(静态链接的文件夹路径))
解决前后端路由的冲突
const fs = require('fs')
const { resolve } = require('path') //文件路径模块
//方法一: 在后端的根文件(index.js)最后写
app.use( async ctx => {
ctx.type = 'html'
ctx.body = fs.createReadStream(resolve(__dirname,'./public/index.html'))
})
//方法二: 在后端的路由文件夹的根路由文件(routers/index.js)最后加
r.get('/:id', ctx => {
ctx.type = 'html'
ctx.body = fs.createReadStream(resolve(__dirname,'../public/index.html'))
})
koa-session模块
const session = require('koa-session')
app.keys = ['secret']
const CONFIG = {
key: 'koa:sess',
maxAge: 86400000,
overwrite: true,
httpOnly: true,
singed: true,
rolling: true
}
app.use(session(CONFIG, app))
cookies的设置和清除
ctx.cookies.set(name, value, {options})
ctx.cookies.get('name')
ctx.cookies.set('name','',{signed:false,maxAge:0})