1

This is something I used to be able to do in 2.2, but in 2.3 I can't.

A simple controller to handle a POST method, and only receive and send application/json content type.

It works for GET/PUT methods, but if POST, it will render home page (html).

<?php

namespace <vendor>\<module>\Controller\Api;

class MyApi extends \Magento\Framework\App\Action\Action
{

    public function execute()
    {
        $result = $this->createResultJson();

        $result->setData([
            'message' => 'All Good.'
        ]);

        $result->setHttpResponseCode(200);

        return $result;
    }


    /**
     * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\Controller\Result\Json
     */
    protected function createResultJson()
    {
        return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON);
    }

}
0

This solves the problem, but after that your module will not work on Magento 2.2 and earlier https://magento.stackexchange.com/a/255082/75860

0

To handle the POST method in your controller class, you have to implement the Magento\Framework\App\Action\HttpPostActionInterface interface:

<?php

namespace Vendor\Module\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;

class MyApi extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
{
    public function execute()
    {
        // ...
    }
}

You can check how the Login controller does it:

vendor/magento/module-customer/Controller/Ajax/Login.php

Also, you should send the Headers correctly, for example:

"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.