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 = {}
/**
* CORS enabled
*-
* @protected
* @type {boolean}
*/
protected corsEnabled: boolean = false
/**
* Register global handlers
*
@@ -306,6 +314,7 @@ export default class Router {
* @returns {Router}
*/
public cors(config?: RouterCorsConfig): Router {
this.corsEnabled = true
this.corsConfig = {
allowOrigin: config?.allowOrigin || '*',
allowMethods: config?.allowMethods || '*',
@@ -385,9 +394,9 @@ export default class Router {
query: {},
body: ''
}
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)
@@ -397,12 +406,15 @@ export default class Router {
if (this.corsConfig.maxAge)
headers.set('Access-Control-Max-Age', this.corsConfig.maxAge.toString())
if (req.method === 'OPTIONS') {
if (!route && 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 (req.headers.has('Content-Type') && req.headers.get('Content-Type')!.includes('json')) {
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 handlers = [...this.globalHandlers, ...route.handlers]
let prevIndex = -1