Can't return HTTP 204 if I echo something

Hi all!
I am using slim4 and writing a simple service. I write something like this when returning the response:

if(..){
    echo "return http 204"
    return $response->withStatus(204);
}

But when I test it using postman, I always get 200. But if I don’t echo anything (remove the echo line), I can get http 204 in the postman.

So can anyone help me for this? How to return HTTP 204 and echo something at the same time? Thank you!!

In Slim you should use the response object to control the HTTP response body and headers.

Example:

$response->getBody()->write('Hello');

https://www.slimframework.com/docs/v4/objects/response.html#the-response-body

I tried this way before. What I did is:

$response->getBody()->write("test 204");
return $response->withStatus(204);

Then when I test it in postman, I do get a 204, but nothing is printed (Ideally it should print “test 204” in this case). So not sure if there is a way to solve this? to print something when returning 204? Thanks!

Ah yes, 204 means “No Content”. So writing some content to the HTTP body will not give you the expected result. Use the status code 200 or 201 (depending on the context) instead.

Got it. Thanks for the help!