52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
/**
|
|
* 跨域中间件
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @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']
|
|
let { hostname, host, protocol } = parse(origin)
|
|
|
|
if (opts.origin.length && hostname) {
|
|
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()
|
|
}
|
|
}
|
JavaScript
100%