core/middleware/cors.js

50 lines
1.1 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
*/
2020-09-18 18:14:47 +08:00
import url from 'url'
2020-09-15 18:35:00 +08:00
2022-07-04 14:57:29 +08:00
export default function (req, res, next) {
2020-09-22 19:58:29 +08:00
var CORS = this.get('cors')
2020-09-15 18:35:00 +08:00
2020-09-22 19:58:29 +08:00
if (CORS.enabled) {
2020-09-15 18:35:00 +08:00
var origin = req.header('origin') || req.header('referer') || ''
var headers = req.header('access-control-request-headers')
2020-09-22 19:58:29 +08:00
var { hostname, host, protocol } = url.parse(origin)
2020-09-15 18:35:00 +08:00
2020-09-22 19:58:29 +08:00
if (CORS.origin.length && hostname) {
2020-09-30 14:25:08 +08:00
var pass = false
for (let it of CORS.origin) {
if (hostname.endsWith(it)) {
pass = true
break
}
}
if (pass === false) {
2020-09-15 18:35:00 +08:00
return res.end('')
}
}
2020-09-30 14:25:08 +08:00
if (CORS.credentials) {
res.set('Access-Control-Allow-Credentials', 'true')
}
2020-09-22 19:58:29 +08:00
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
2021-04-14 15:34:58 +08:00
res.set('Access-Control-Allow-Methods', 'GET,HEAD,POST,PUT,DELETE,PATCH')
2020-09-22 19:58:29 +08:00
2020-09-15 18:35:00 +08:00
if (headers) {
res.set('Access-Control-Allow-Headers', headers)
}
2020-09-22 19:58:29 +08:00
if (CORS.maxAge) {
res.set('Access-Control-Max-Age', CORS.maxAge)
2020-09-15 18:35:00 +08:00
}
2020-09-22 19:58:29 +08:00
2020-09-15 18:35:00 +08:00
if (req.method === 'OPTIONS') {
return res.end('')
}
}
next()
}