404 Not Found error in preflight OPTIONS when executing a PUT method in CakePHP API with axios in React App

时间:2019-05-31 11:37:45

标签: reactjs apache cakephp cakephp-3.0

So, we have an API with CakePHP 3.7. We are using resources to generate CRUD methods. The API is hosted in a server with apache2 and is accessed through a manager app using React (this app is a microservice). The manager makes the calls through axios and is correctly managing the GET, POST and HEAD requests (simple CORS requests) but we're having problems when it comes to more complex requests such as PUT or DELETE.

When executing PUT or DELETE requests it makes a preflight OPTIONS request and it returns a 404 Not Found error. And some messages in console related with CORS which are:

We already tried several fixes, such as using CakePHP CORS plugin, adding CORS Headers in the response in the beforeRender and beforeFilter methods of AppController and also adding CORS headers in the apache, none of this seams to be working.

    private function setCorsHeaders() {
        $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }

    public function beforeRender(Event $event)
    {
        $this->setCorsHeaders();
    }

    public function beforeFilter(Event $event)
    {
        if($this->request->is('options')) {
            $this->setCorsHeaders();
            return $this->response;
        }
    }
Header set Access-Control-Expose-Headers "X-Total-Pages"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"

The expected behaviour is that the PUT and DELETE methods are executed properly (the preflight OPTIONS should pass successfully). Any help is apreciated.

1 个答案:

答案 0 :(得分:0)

在CakePHP> = 3.4中,许多方法treated as immutableHttp\Response对象。在$this->request->cors()上调用的方法链使用CorsBuilder类将所需的标头排队在不变的响应上,该响应在调用build()时返回。

尝试将带有排队标题的CorsBuilder::build()的收益分配给$this->response

    private function setCorsHeaders() {
        $this->response = $this->response->cors($this->request)
            ->allowOrigin(['*'])
            ->allowMethods(['*'])
            ->exposeHeaders(['X-Total-Pages'])
            ->maxAge(800)
            ->build();
    }