core/middleware/cors.js

52 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2020-09-15 18:35:00 +08:00
/**
2020-09-18 18:14:47 +08:00
* 跨域中间件
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 14:55:49
2020-09-15 18:35:00 +08:00
*/
2023-10-27 19:16:59 +08:00
import { parse } from 'node:url'
export function createCors() {
return function (req, res, next) {
2023-11-01 18:46:47 +08:00
let opts = this.get('cors')
2023-10-27 19:16:59 +08:00
if (opts.enabled) {
2023-11-01 18:46:47 +08:00
let origin = req.header('origin') || req.header('referer') || ''
let headers = req.header('access-control-request-headers')
let { hostname, host, protocol } = parse(origin)
2023-10-27 19:16:59 +08:00
if (opts.origin.length && hostname) {
2023-11-01 18:46:47 +08:00
let pass = false
2023-10-27 19:16:59 +08:00
for (let it of opts.origin) {
if (hostname.endsWith(it)) {
pass = true
break
}
}
if (pass === false) {
return res.end('')
2020-09-30 14:25:08 +08:00
}
}
2023-10-27 19:16:59 +08:00
if (opts.credentials) {
res.set('Access-Control-Allow-Credentials', 'true')
2020-09-15 18:35:00 +08:00
}
2020-09-30 14:25:08 +08:00
2023-10-27 19:16:59 +08:00
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
res.set('Access-Control-Allow-Methods', req.method)
2020-09-22 19:58:29 +08:00
2023-10-27 19:16:59 +08:00
if (headers) {
res.set('Access-Control-Allow-Headers', headers)
}
2020-09-22 19:58:29 +08:00
2023-10-27 19:16:59 +08:00
if (opts.maxAge) {
res.set('Access-Control-Max-Age', opts.maxAge)
}
2020-09-22 19:58:29 +08:00
2023-10-27 19:16:59 +08:00
if (req.method === 'OPTIONS') {
return res.end('')
}
2020-09-15 18:35:00 +08:00
}
2023-10-27 19:16:59 +08:00
next()
2020-09-15 18:35:00 +08:00
}
}