core/middleware/cors.js

52 lines
1.2 KiB
JavaScript

/**
* 跨域中间件
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 14:55:49
*/
import { parse } from 'node:url'
export function createCors() {
return function (req, res, next) {
let opts = this.get('cors')
if (opts.enabled) {
let origin = req.header('origin') || req.header('referer') || ''
let headers = req.header('access-control-request-headers')
let { hostname, host, protocol } = parse(origin)
if (opts.origin.length && hostname) {
let pass = false
for (let it of opts.origin) {
if (hostname.endsWith(it)) {
pass = true
break
}
}
if (pass === false) {
return res.end('')
}
}
if (opts.credentials) {
res.set('Access-Control-Allow-Credentials', 'true')
}
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
res.set('Access-Control-Allow-Methods', req.method)
if (headers) {
res.set('Access-Control-Allow-Headers', headers)
}
if (opts.maxAge) {
res.set('Access-Control-Max-Age', opts.maxAge)
}
if (req.method === 'OPTIONS') {
return res.end('')
}
}
next()
}
}
一个轻量级的,易学的,拓展性灵活的 nodejs MVC 框架, 5 分钟即可上手。取自"Give me five"之意, 一切就是这么简单
JavaScript 100%