Calling Javascript fetch with POST method to SLIM 4

I am trying to access an authentication from a Vue 3-app via my own SLIM 4-application but cannot get the POST-method variables into my SLIM-app.

My call from Vue-app is as follows:

const response = await fetch('http://slim4-api.mydomain.net/session/new', {
            method: 'POST',
            body: JSON.stringify({
                email: payload.email,
                password: payload.password,
            })
        });

Slim route is as follows:

 $app->post('/session/{action}', MySession::class)->setName('session');

And the relevant part of Slim 4 app is:

public function handle(ServerRequestInterface $request): ResponseInterface
{
$action = $request->getAttribute(‘action’, “new”);
$post_data = $request->getBody();
$post_data = $request->getParsedBody();
$data = [];
if ($action == “new”) {
$data[“token”] = $this->getToken();
// $data[“post_data”] = $post_data;
}
$response = new Response();
$response->getBody()->write(json_encode($data));
return $response->withHeader(‘Content-Type’, ‘application/json’);
}

The problem is bold statements with $request->getParsedBody(); which always gives null as a result. If I output to $this->logger->info getBody, the JSON-encoding of the POST JSON data prints, but I haven’t found any way to really use the posted data.

According what I have read, the getParsedBody SHOULD be the right way to handle this, but… it gives me nothing…

I am really a long time (I mean really really) PHP user and using json_decode is something I do in most of these days, but still this mechanism in SLIM 4 overwhelms me like anything.

Could anyone show even a ray of light to this situation which I just don’t get

wbr hank

Hmmm, it seems that

file_get_contents('php://input')

gives me the POST data I’m looking for…

Still strange that docs talk about getParsedBody()-method…

But anyhow, this seems to work now…

hank

The BodyParsing middleware only parses the body of the HTTP request if the Content-Type header was transmitted correctly.

Just add this header to make it work:

// ...
headers: {
    'Content-Type': 'application/json'
},

Thank you, that was the (other) missing piece.

I also had to add

header("Access-Control-Allow-Headers: Content-Type");

to not get the CORS-error, but after that everything works great.

Thank you

hank

Try this json_decode(app()->request->getBody(),true)