/** * 跨域中间件 * @author yutent * @date 2020/09/18 14:55:49 */ import { parse } from 'node:url' export function createCors() { return function (req, res, next) { let opts = this.get('cors') if (opts.enabled) { let origin = req.headers['origin'] || req.headers['referer'] || '' let headers = req.headers['access-control-request-headers'] if (!origin) { return next() } let { hostname, host, protocol } = parse(origin) if (opts.origin.length) { let pass = false for (let it of opts.origin) { if (hostname.endsWith(it)) { pass = true break } } if (pass === false) { return (res.body = null) } } if (opts.credentials) { res.set('Access-Control-Allow-Credentials', 'true') } res.set('Access-Control-Allow-Origin', `${protocol}//${host}`) res.set('Access-Control-Allow-Methods', '*') if (headers) { res.set('Access-Control-Allow-Headers', headers) } if (opts.maxAge) { res.set('Access-Control-Max-Age', opts.maxAge) } if (req.method === 'OPTIONS') { return (res.body = null) } } next() } }