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.header('origin') || req.header('referer') || ''
|
|
let headers = req.header('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.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()
|
|
}
|
|
}
|
JavaScript
100%