'Magento 2 - Custom rest api endpoint for PDF download - net::ERR_HTTP2_PROTOCOL_ERROR 200

  • I have created custom rest api endpoint in magento for downloading pdf file.

  • When testing it locally: From separate react JS project I am sending request to that endpoint and file is downloaded successfuly. http/1.1 protocol is used (checked in google chrome dev tools, network tab).

  • After deployment to staging servers, when I try to make request between staging servers from reactJS project to magento2 project, then upon sending request it takes 30-40 seconds without getting any response and then error is shown in console. There is not anything in the error logs. http2 protocol is used (not sure if that can be a reason for issue).

Failed to fetch - net::ERR_HTTP2_PROTOCOL_ERROR 200

Here is the piece of php code for downloading pdf file:

    ...
    $filename = $outputFileName . time() . '.' . $extension;
    $directoryTmpWrite = $this->filesystem->getDirectoryWrite(DirectoryList::TMP);
    $directoryTmpWrite->writeFile($filename, $fileContent);

    return $this->fileFactory->create(
        $outputFileName . '.' . $extension,
        [
            'type' => 'filename',
            'value' => $filename,
            'rm' => true,
        ],
        DirectoryList::TMP, //basedir
        'application/octet-stream',
        ''
    );


Solution 1:[1]

How I resolved my issue?

I had to turn on output buffering in php in magento, to ensure that no output has been sent from a script and instead of that output has been store to a buffer and then sent all together from a script when script execution is finished.

So ob_start() fixed my issue. Right before return statement.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Denis2310