Hi All,
We have the below routes , when the page is loaded it call’s the route “/f301” and load the page with default list of server(Active Servers) then in our page we have a drop down box with options (Active Server / Inactive Server) so the call to the route “/f301/{rvalue}” is invoke another ajax call to get the respective servers( active or inactive) based on user choice. this code works perfectly in Slim3 (without the concept of middleware) where as in Slim 4 with the middelware this does not work, hence request your help on this. Searching in this blog stated to addd the below method to the middleware and we tried to add the same in our authendication middell ware but no luck
route.php
$app->group('', function(RouteCollectorProxy $group) {
$group->get('/f301', function($request, $response) {
return $this->get('view')->render($response, 'page_serverlist.html')->withHeader('Content-Type', 'application/json');
})->setName('f301');
$group->get('/f301/{rvalue}', function($request, $response, $args) {
$sl = new serverinfo();
$type = $args['rvalue'];
$instdata = $sl->getServerInfo($type);
$response->getBody()->write($instdata);
return $response->withHeader('Content-Type', 'application/json');
})->setName('f301');
});
Code found in this blog
private function isAjax(RequestInterface $request)
{
return strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest';
}
**AuthMiddleware.php
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
use Psr\Http\Server\MiddlewareInterface;
final class AuthMiddleware implements MiddlewareInterface {
private $responseFactory;
public function isAjax(RequestInterface $request) { return strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest'; }
public function __construct(ResponseFactoryInterface $responseFactory) { $this->responseFactory = $responseFactory; }
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
if(empty($route)) { throw new NotFoundException($request, $response); }
$routeName = (string)$route->getName();
$publicRoutesArray = array('f204');
if(empty($_SESSION['user']) && in_array($routeName, $publicRoutesArray)) {
$routeParser = RouteContext::fromRequest($request)->getRouteParser();
$url = (string)$routeParser->urlFor('login');
$response = $handler->handle($request);
return $response->withHeader('Location', $url)->withStatus(302);
} else { return $handler->handle($request); }
}
}
?>