当返回http码为401时,Koa将自动去掉allow origin,导致返回的错误变成origin not allowed,这种时候前端无法捕获到这个错误。
解决方法:
使用koa-cors,设置options,修改抛出错误的方式。
// 使用koa-cors
// 注意设置 keepHeadersOnError: true
import cors from '@koa/cors'
app.use(cors({
origin: (ctx) => {
let origin = ctx.request.headers.origin || '';
const allowedOrigins = ['https://example.site', 'file://'];
if (allowedOrigins.includes(origin) || origin.includes('localhost')) {
return origin
} else {
return null
}
},
allowHeaders: 'Authorization, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With',
credentials: true,
keepHeadersOnError: true
}))
//抛出错误让前端捕获
ctx.throw(401,{ code: -2, message: '身份验证失败!'});