1
0
This commit is contained in:
2022-10-02 23:50:48 +02:00
parent 8e58dc349e
commit a786262ec6

View File

@@ -165,6 +165,14 @@ export default class Router {
*/ */
protected corsConfig: RouterCorsConfig = {} protected corsConfig: RouterCorsConfig = {}
/**
* CORS enabled
*-
* @protected
* @type {boolean}
*/
protected corsEnabled: boolean = false
/** /**
* Register global handlers * Register global handlers
* *
@@ -306,6 +314,7 @@ export default class Router {
* @returns {Router} * @returns {Router}
*/ */
public cors(config?: RouterCorsConfig): Router { public cors(config?: RouterCorsConfig): Router {
this.corsEnabled = true
this.corsConfig = { this.corsConfig = {
allowOrigin: config?.allowOrigin || '*', allowOrigin: config?.allowOrigin || '*',
allowMethods: config?.allowMethods || '*', allowMethods: config?.allowMethods || '*',
@@ -385,24 +394,27 @@ export default class Router {
query: {}, query: {},
body: '' body: ''
} }
const headers = new Headers() const headers = new Headers()
const route = this.getRoute(req)
if (this.corsEnabled) {
if (this.corsConfig.allowOrigin)
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin)
if (this.corsConfig.allowMethods)
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods)
if (this.corsConfig.allowHeaders)
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders)
if (this.corsConfig.maxAge)
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
if (this.corsConfig.allowOrigin) if (!route && req.method === 'OPTIONS') {
headers.set('Access-Control-Allow-Origin', this.corsConfig.allowOrigin) return new Response(null, {
if (this.corsConfig.allowMethods) headers,
headers.set('Access-Control-Allow-Methods', this.corsConfig.allowMethods) status: this.corsConfig.optionsSuccessStatus
if (this.corsConfig.allowHeaders) })
headers.set('Access-Control-Allow-Headers', this.corsConfig.allowHeaders) }
if (this.corsConfig.maxAge)
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
if (req.method === 'OPTIONS') {
return new Response(null, {
headers,
status: this.corsConfig.optionsSuccessStatus
})
} }
if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
if (['POST', 'PUT', 'PATCH'].includes(req.method)) { if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) { if (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
try { try {
@@ -418,9 +430,6 @@ export default class Router {
} }
} }
} }
const route = this.getRoute(req)
if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
const res: RouterResponse = { headers } const res: RouterResponse = { headers }
const handlers = [...this.globalHandlers, ...route.handlers] const handlers = [...this.globalHandlers, ...route.handlers]
let prevIndex = -1 let prevIndex = -1