core/middleware/credentials.js

38 lines
1.0 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
*/
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-15 18:35:00 +08:00
var supportCredentials = this.get('supportCredentials')
var credentialsRule = this.get('credentialsRule')
var credentialsMaxAge = this.get('credentialsMaxAge')
if (supportCredentials) {
var origin = req.header('origin') || req.header('referer') || ''
var headers = req.header('access-control-request-headers')
2020-09-18 18:14:47 +08:00
origin = url.parse(origin)
2020-09-15 18:35:00 +08:00
if (credentialsRule && origin.hostname) {
if (!credentialsRule.test(origin.hostname)) {
return res.end('')
}
}
res.set('Access-Control-Allow-Credentials', 'true')
res.set('Access-Control-Allow-Origin', `${origin.protocol}//${origin.host}`)
if (headers) {
res.set('Access-Control-Allow-Headers', headers)
}
if (credentialsMaxAge) {
res.set('Access-Control-Max-Age', credentialsMaxAge)
}
if (req.method === 'OPTIONS') {
return res.end('')
}
}
next()
}