1

I am developing an CakePHP app that the Models for my ReactJS application, but I have run into a problem using Axios to retrieve a dynamically created json from one of the endpoints in the CakePHP application.

The action in the controller looks like this:

public function bootstrap($name = null){
    $this->autoRender = false;
    $config = $this->Themes->getJson($name);
    $config += $this->systemVars();
    $output = json_encode($config);
    $this->response
    ->withHeader('Access-Control-Allow-Origin','*')
    ->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
    ->withHeader('Access-Control-Max-Age','8600')
    ->withType('application/json')
    ->withStringBody($output);
    return $this->response;
}

and the axios request in my React app looks like this:

axios.get('https://demo.axistaylor.com/ccsllc/themes/json')
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Everything seems to work fine except this the response that is printed to the console when I run the react app.

{
   config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, 
   timeout: 0, xsrfCookieName: "XSRF-TOKEN", …},
   data:"",
   headers:{pragma: "no-cache", content-type: "text/html; charset=UTF-8", 
cache-control: "no-store, no-cache, must-revalidate", expires: "Thu, 19 Nov 1981 08:52:00 GMT"},
   request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …},
   status: 200,
   statusText: "OK",
   …
}

The data comeback as an empty string "". I have tried changing the method of setting the body and headers, even reverting to the methods supported by prior versions of CakePHP, eg. $this->response->header(…)->body(…), and the results are the same. The endpoint listed in the axios request is public so you can test it yourself. https://demo.axistaylor.com/ccsllc/themes/json

Geoff Taylor
  • 496
  • 3
  • 17
  • 2
    **https://stackoverflow.com/questions/43184833/cakephp3-4-how-to-send-a-json-object-response** – ndm Jan 28 '18 at 21:04
  • The problem still persist but thanks for that. I had no idea $this->response was partial immutable. I've changed the my code to fit the new requirements of 3.5 – Geoff Taylor Jan 28 '18 at 21:12
  • Sorry, it worked. I changes had been commited to my server before I tested. Thanks a lot. – Geoff Taylor Jan 28 '18 at 21:23

1 Answers1

1

The problem was the initial $this->response is immutable in CakePHP 3.5+, and has to be reassigned with header and body in one statement like this.

$this->response = $this->response
->withHeader('Access-Control-Allow-Origin','*')
->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
->withHeader('Access-Control-Max-Age','8600')
->withType('application/json')
->withStringBody($output);

for information look as the answer to the question here provided by ndm

Geoff Taylor
  • 496
  • 3
  • 17