I was getting this error when sending response to the get type ajax controller.
the code was like below.
<?php
declare(strict_types=1);
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Response\Http;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\Result\PageFactory;
use Psr\Log\LoggerInterface;
class Download implements HttpGetActionInterface
{
protected $resultPageFactory;
protected $serializer;
protected $logger;
protected $http;
public function __construct(
PageFactory $resultPageFactory,
Json $json,
LoggerInterface $logger,
Http $http
) {
$this->resultPageFactory = $resultPageFactory;
$this->serializer = $json;
$this->logger = $logger;
$this->http = $http;
}
public function execute()
{
try {
return $this->jsonResponse('your response');
} catch (LocalizedException $e) {
return $this->jsonResponse($e->getMessage());
} catch (\Exception $e) {
$this->logger->critical($e);
return $this->jsonResponse($e->getMessage());
}
}
public function jsonResponse($response = '')
{
$this->http->getHeaders()->clearHeaders();
$this->http->setHeader('Content-Type', 'application/json');
return $this->http->setBody(
$this->serializer->serialize($response)
);
}
}
?>