koa2-cors应答跨域请求实现
1. 安装 koa2-cors
npm install --save koa2-cors
2. 在 app.js 中 放在最顶部 (全局跨域)
const cors = require('koa2-cors')
// 配置 cors 跨域
app.use(cors({
//设置允许来自指定域名请求
origin: (ctx) => {
return '*' // 允许来自所有域名请求
},
maxAge: 5, //指定本次预检请求的有效期,单位为秒。
credentials: true, //是否允许发送Cookie
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}))
全局错误拦截
1. 封装拦截中间件
errorHandler.js 文件
// 全局处理异常
module.exports = (app) => {
app.use(async (ctx, next) => {
let status = null
try {
await next()
status = ctx.status
} catch (err) {
// 抛出错误
console.log('err', err)
console.log('ctx', ctx)
status = 500
ctx.body = {
code: 500,
url: ctx.request.url,
Error: err.message
}
}
ctx.response.status = status
})
}
2. 在 app.js 中
const errorHandler = require('./middlweare/errorHandler');
// 全局处理错误
errorHandler(app)