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
|
|
|
|
2020-09-16 14:08:06 +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) {
|
|
|
|
if (!CORS.origin.includes(hostname)) {
|
2020-09-15 18:35:00 +08:00
|
|
|
return res.end('')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
res.set('Access-Control-Allow-Credentials', 'true')
|
2020-09-22 19:58:29 +08:00
|
|
|
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
|
|
|
|
|
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()
|
|
|
|
}
|