core/middleware/cors.js

56 lines
1.3 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-08 09:33:12 +08:00
let origin = req.headers['origin'] || req.headers['referer'] || ''
let headers = req.headers['access-control-request-headers']
2024-06-27 18:38:01 +08:00
if (!origin) {
return next()
}
2023-11-01 18:46:47 +08:00
let { hostname, host, protocol } = parse(origin)
2023-10-27 19:16:59 +08:00
2024-06-27 18:38:01 +08:00
if (opts.origin.length) {
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) {
2023-11-08 09:33:12 +08:00
return (res.body = null)
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}`)
2024-02-23 20:54:26 +08:00
res.set('Access-Control-Allow-Methods', '*')
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') {
2023-11-08 09:33:12 +08:00
return (res.body = null)
2023-10-27 19:16:59 +08:00
}
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
}
}