/** * 跨域中间件 * @author yutent * @date 2020/09/18 14:55:49 */ import { parse } from 'node:url' export function createCors() { return function (req, res, next) { var opts = this.get('cors') if (opts.enabled) { var origin = req.header('origin') || req.header('referer') || '' var headers = req.header('access-control-request-headers') var { hostname, host, protocol } = parse(origin) if (opts.origin.length && hostname) { var pass = false for (let it of opts.origin) { if (hostname.endsWith(it)) { pass = true break } } if (pass === false) { return res.end('') } } if (opts.credentials) { res.set('Access-Control-Allow-Credentials', 'true') } res.set('Access-Control-Allow-Origin', `${protocol}//${host}`) res.set('Access-Control-Allow-Methods', req.method) 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.end('') } } next() } }