core/middleware/cors.js

52 lines
1.2 KiB
JavaScript
Raw 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) {
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('')
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
}
}