Can't access CakePHP API endpoint via ReactJS. Only through the browser

416 Views Asked by At

I am trying to build a REST API for my server via CakePHP. I thought I had it working as I can receive the JSON responses via the web browser however when trying to access the same route via ReactJS, the Controllers Action is not actually firing.

Reading the CakePHP docs I really should only have to implement these lines of code to get the API working (According to the docs) and I did:

/config/routes.php

Router::scope('/', function($routes) { $routes->setExtensions(['json']); $routes->resources('Users'); });

Here is the API Endpoint I want to hit:

`public function signUp() {
     $file = fopen("error_log.txt", "w");
     $txt = "firing endpoint";
     $fwrite($file, $txt);
     $fclose($file);
     $response = $this->response;
     $responseText = [
         "status" => "200",
         "message" => "User added successfully"
     ];
     $response = $response->withType("application/json")
         ->withStringBody(json_encode($responseText));
     return $response;
}`

Here I am successfully hitting that endpoint via the browser. My log message also appears in the error_log.txt file

enter image description here

Here is where I'm making a request via ReactJS:

handleRequest = () => { console.log('making request'); axios({ method: 'get', url: 'https://157.230.176.243/users/register.json', data: { email: this.state.email, password: this.state.password } })
.then(function(response) { console.log('got response'); console.log(response); })
.catch(function(error) { console.log('got error'); console.log(error); })
.then(function(data) { console.log('always executed'); console.log(data); }); }

When I make this request via ReactJS I get a XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"

Also when making this request via ReactJS my log message does not get written to error_log.txt

1

There are 1 best solutions below

0
On

Ok I finally figured out what was wrong. I have my React Development server running on

157.230.176.243:3001

and my CakePHP API served on that same server,

157.230.176.243

React didn't like it that I was passing the full URL of the API to the fetch()

call. I switched my React code to

url: "/users/register.json" and it works fine.