Post request return null

Hi. Please HELP.
Such problem. I do everything according to the video guide. When I send data via postman and process it via getParsedBody (), it returns null.

    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;
    use Slim\Factory\AppFactory;

    require __DIR__ . '/../vendor/autoload.php';

    $app = AppFactory::create();
    $app->get('/', function (Request $request, Response $response) {
        $response->getBody()->write("Hello, World!");

        return $response;
    });

    $app->post('/users', function (Request $request, Response $response, $args) {
        header("Content-Type: application/json;");
        $requestData = $request->getParsedBody();
        print_r($requestData);
        return $response;
    });

IMG

Summary




getParsedBody (), it returns null.

  1. Have you tried to add the BodyParsingMiddleware?
$app->addBodyParsingMiddleware();
  1. Your (HTTP) client must send the correct request header value Content-Type: application/json

image

Read more: Difference between Accept and Content-Type HTTP headers

header(“Content-Type: application/json;”);

Better don’t use the vanilla header() function in Slim. To manipulate the response headers use the $response object instead.

Cannot register two routes…

Make sure, that your routes are not overlapping. Don’t define the same route twice.

Thanks for the answer. But it didn’t help. Can there be more tips?
I have already spent a lot of time searching for a solution to this problem…

Summary



The request Content-Type is missing now, it’s required.

All the same, friend

Summary


Please show us your request body content.

I should have sent it like this? Through the body and not params? :slight_smile:

I should have sent it like this? Through the body and not params?

Yes, look at your first question :slight_smile:

getParsedBody()

$requestData = $request->getParsedBody();

Maybe I just don’t get your question right. Are you trying to send JSON or form-data to the server?

If JSON set the correct Content-Type Header and switch the mode from form-data to RAW -> JSON

Route processes the request. Everything is working out well and now I need to send requests like this?

I was given a test task. I need to make a simple api to output, add, and delete a user saved to a json file

Everything is working out well and now I need to send requests like this?

If you want to implement a working RESTful API with JSON then yes :slight_smile:

Thank you very much, friend. I can’t tell you how grateful I am. I stayed up all night trying to solve the problem :slight_smile:

$requestData = $request->getBody()->getContents();