About writing the middleware

Hello, I’m new in slim frame work.

I would like to know what is the different with the code below

$app->add(function ($request, $response, $next) {
    $response = $next($request, $response);
    return $response
            ->withHeader('Access-Control-Allow-Origin', 'https://mysite.com')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});

and this

$app->add(function ($request, $response, $next) {
    $response = $next($request, $response);
    $response->withHeader('Access-Control-Allow-Origin', 'https://mysite.com')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    return $response;
});

when I use the second statement, the header seem like won’t send out.

Can anybody give me help.

The middleware can have code running before or after the response is sent out.
In your case you want to change the reponse before its sent.
Try the code bellow

$app->add(function ($request, $response, $next) {
    $response = $response
        ->withHeader('Access-Control-Allow-Origin', 'https://mysite.com')
        ->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($request, $response);
});
1 Like