0

I am trying to implement http DELETE. The app is written with php and slim3 framework. The frontend is angular 2.

If the pattern looks like:$slimApp->delete('/delete', ...) everything is fine.

As soon as I introduce params like: $slimApp->delete('/delete/{id}', ...) I get the following error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already read the docs https://www.slimframework.com/docs/cookbook/enable-cors.html but however I cannot get it work.

Here is my middleware:

<?php

class MyMiddleware {

    public function __invoke(Request $req, Response $res, $next) {
        $res->withHeader('Access-Control-Allow-Origin', 'http://localhost:8100')
            ->withHeader('Access-Control-Allow-Credentials', 'true')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

        return $next($req, $res);
    }

}

$app = new \Slim\App([
    "settings"  => [
        "determineRouteBeforeAppMiddleware" => true
    ]
]);

$app->add(new MyMiddleware());

Any ideas what could be the problem?

kemal89
  • 931
  • 2
  • 8
  • 20

2 Answers2

1

The response is immutable, reassign the variable.

public function __invoke(Request $req, Response $res, $next) {
    $res = $res->withHeader('Access-Control-Allow-Origin', 'http://localhost:8100')
        ->withHeader('Access-Control-Allow-Credentials', 'true')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    return $next($req, $res);
}
jmattheis
  • 10,494
  • 11
  • 46
  • 58
0

OK solved the problem. The .htaccess just did not let the request "reach" the code. So I just needed to optimize the rules.

kemal89
  • 931
  • 2
  • 8
  • 20