diff --git a/config/autoload/middleware-pipeline.global.php b/config/autoload/middleware-pipeline.global.php index 8a393ce1..ab903ac9 100644 --- a/config/autoload/middleware-pipeline.global.php +++ b/config/autoload/middleware-pipeline.global.php @@ -1,4 +1,5 @@ [ 'middleware' => [ ApplicationFactory::ROUTING_MIDDLEWARE, + ], + 'priority' => 10, + ], + + 'rest' => [ + 'path' => '/rest', + 'middleware' => [ + Middleware\CrossDomainMiddleware::class, + ], + 'priority' => 5, + ], + + 'post-routing' => [ + 'middleware' => [ Helper\UrlHelperMiddleware::class, ApplicationFactory::DISPATCH_MIDDLEWARE, ], diff --git a/config/autoload/services.global.php b/config/autoload/services.global.php index 92a4adce..08fedf55 100644 --- a/config/autoload/services.global.php +++ b/config/autoload/services.global.php @@ -49,6 +49,7 @@ return [ Middleware\Rest\ResolveUrlMiddleware::class => AnnotatedFactory::class, Middleware\Rest\GetVisitsMiddleware::class => AnnotatedFactory::class, Middleware\Rest\ListShortcodesMiddleware::class => AnnotatedFactory::class, + Middleware\CrossDomainMiddleware::class => InvokableFactory::class, ], 'aliases' => [ 'em' => EntityManager::class, diff --git a/src/Middleware/CrossDomainMiddleware.php b/src/Middleware/CrossDomainMiddleware.php new file mode 100644 index 00000000..c762ed83 --- /dev/null +++ b/src/Middleware/CrossDomainMiddleware.php @@ -0,0 +1,51 @@ +hasHeader('X-Requested-With') + && strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest' + ) { + $response = $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') + ->withHeader('Access-Control-Max-Age', '1000') + ->withHeader('Access-Control-Allow-Origin', '*') + ->withHeader('Access-Control-Allow-Headers', '*'); + } + + return $response; + } +} diff --git a/src/Middleware/Rest/GetVisitsMiddleware.php b/src/Middleware/Rest/GetVisitsMiddleware.php index b932622d..1a1b973b 100644 --- a/src/Middleware/Rest/GetVisitsMiddleware.php +++ b/src/Middleware/Rest/GetVisitsMiddleware.php @@ -57,7 +57,7 @@ class GetVisitsMiddleware implements MiddlewareInterface public function __invoke(Request $request, Response $response, callable $out = null) { $shortCode = $request->getAttribute('shortCode'); - + try { $visits = $this->visitsTracker->info($shortCode);