I’m adding a middle-ware to check or verify if the request data from the client is a valid json
then return an error message.
But got stock with this error. Please help me here
<br />
<b>Fatal error</b>: Uncaught Error: Cannot instantiate interface
Psr\Http\Message\ResponseInterface in
C:\xampp\htdocs\learning_app\public\index.php:51
Stack trace:
#0 C:\xampp\htdocs\learning_app\public\index.php(59): Renz-
>handle(Object(Slim\Psr7\Request))
#1 C:\xampp\htdocs\learning_app\vendor\slim\slim\Slim\MiddlewareDispatcher.php(283):
{closure}(Object(Slim\Psr7\Request), Object(Renz))
#2 C:\xampp\htdocs\learning_app\vendor\slim\slim\Slim\MiddlewareDispatcher.php(81):
class@anonymous->handle(Object(Slim\Psr7\Request))
#3 C:\xampp\htdocs\learning_app\vendor\slim\slim\Slim\App.php(211):
Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request))
#4 C:\xampp\htdocs\learning_app\vendor\slim\slim\Slim\App.php(195): Slim\App-
>handle(Object(Slim\Psr7\Request))
#5 C:\xampp\htdocs\learning_app\public\index.php(130): Slim\App->run()
#6 {main}
thrown in <b>C:\xampp\htdocs\learning_app\public\index.php</b> on line <b>51</b><br />
here is my code
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use ReallySimpleJWT\Token;
use ReallySimpleJWT\Parse;
use ReallySimpleJWT\Jwt;
use ReallySimpleJWT\Validate;
use ReallySimpleJWT\Encode;
use ReallySimpleJWT\Exception\ValidateException;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config/connection.php';
$app = AppFactory::create();
$app->setBasePath('/learning_app');
class Renz implements RequestHandler{
public function handle(Request $request): Response{
$data = $request->getBody();
try{
$json = json_decode($data);
$status = 200;
$headers = [
"Content-Type" => "application/json"
];
$body = array(
"ok" => true,
"message" => "mayat"
);
}catch(Exception $e){
$status = 500;
$headers = [
"Content-Type" => "application/json"
];
$body = array(
"ok" => false,
"message" => "invalid request"
);
}
$response = new Response($status, $headers, $body); //this is line 51 in the error
return $response;
}
}
$beforeMiddleware = function (Request $request, RequestHandler $handler) {
$handler = new Renz();
$response = $handler->handle($request);
return $response;
};
$app->add($beforeMiddleware);
.....
$app->run();