简体   繁体   English

无法通过ReactJS访问CakePHP API端点。 仅通过浏览器

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

I am trying to build a REST API for my server via CakePHP. 我正在尝试通过CakePHP为我的服务器构建REST API。 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. 我以为可以正常工作,因为我可以通过Web浏览器接收JSON响应,但是当尝试通过ReactJS访问相同的路由时,Controllers Action实际上并未触发。

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: 阅读CakePHP文档,我真的只需要实现以下代码行即可使API正常工作(根据文档),我做到了:

/config/routes.php

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

Here is the API Endpoint I want to hit: 这是我要访问的API端点:

`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 我的日志消息也出现在error_log.txt文件中

在此处输入图片说明

Here is where I'm making a request via ReactJS: 这是我通过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" 当我通过ReactJS发出此请求时,我得到的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 另外通过ReactJS发出此请求时,我的日志消息未写入error_log.txt

Ok I finally figured out what was wrong. 好的,我终于弄清楚了什么地方出了问题。 I have my React Development server running on 我的React Development服务器正在运行

157.230.176.243:3001

and my CakePHP API served on that same server, 而我的CakePHP API则在同一台服务器上提供,

157.230.176.243

React didn't like it that I was passing the full URL of the API to the fetch() React不喜欢我将API的完整URL传递给fetch()

call. 呼叫。 I switched my React code to 我将我的React代码切换到

url: "/users/register.json" and it works fine. url: "/users/register.json" ,它可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM