phpjsonlaravelphp-7laravel-5.8

Laravel sends JSON headers in body


I have the following class that handles JSON responses for me:

<?php
namespace BulkTransactionalSMS\Http\Handlers\Response;

use Symfony\Component\HttpFoundation\Response;

class JsonResponseHandler implements ResponseHandlerInterface
{
    /**
     * @param string $message
     * @return Response
     */
    public function errorResponse(string $message): Response
    {
        return response()->json([
            'status' => 'error',
            'message' => $message
        ]);
    }

    /**
     * @param array $successDetails
     * @return Response
     */
    public function successResponse(array $successDetails = []): Response
    {
        $response = array_merge(['status' => 'success'], $successDetails);
        return response()->json($response);
    }
}

All JSON responses is handled by this class because then it's uniform and easy to change. I have tried this class as it is as well as with Response::json() and both yield the same result.

JSON headers are being sent back which is screwing with jQuery handling the response. This is an example call, and what I'm getting back:

// Example call
$jsonResponseHandler = new JsonResponseHandler();
return $jsonResponseHandler->errorResponse('This is not working');

// Returns this:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Tue, 12 Mar 2019 06:15:28 GMT

{"status":"error","message":"This is not working"}

// Expected return:
{"status":"error","message":"This is not working"}

The route that is called (via Ajax) is set up like this:

Route::post('/upload-file', 'UploadController@uploadFile');

And this is what the target function looks like:

/**
 * @param Request $request
 * @return Response
 */
public function uploadFile(Request $request)
{
    $fileHandler = new FileUploadHandler(
        new MessagesRepository(new Message()),
        new JsonResponseHandler(),
        new Hasher()
    );
    return $fileHandler->uploadFile($request);
}

Why is it returning the headers in the body and how do I fix it?

EDIT 1

Here is FileUploadHandler.php.


Solution

  • As I went through the file I uploaded for FatBoyXPC, I saw that my typecasting for the function was string. That's why it broke. Here's how I fixed it:

    public function uploadFile(Request $request): string
    {
        // do stuff
    }
    

    It's supposed to be:

    public function uploadFile(Request $request): \Symfony\Component\HttpFoundation\Response
    {
        // do stuff
    }