0

我正在尝试通过 CakePHP 为我的服务器构建一个 REST API。我以为我可以正常工作,因为我可以通过 Web 浏览器接收 JSON 响应,但是当尝试通过 ReactJS 访问相同的路由时,控制器操作实际上并没有触发。

阅读 CakePHP 文档我真的应该只需要实现这些代码行来让 API 工作(根据文档),我做到了:

/config/routes.php

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

这是我想要访问的 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;
}`

在这里,我通过浏览器成功地到达了那个端点。我的日志消息也出现在error_log.txt文件中

在此处输入图像描述

这是我通过 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); }); }

当我通过 ReactJS 提出这个请求时,我得到一个XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"

此外,当通过 ReactJS 发出此请求时,我的日志消息不会被写入error_log.txt

4

1 回答 1

1

好的,我终于弄清楚出了什么问题。我的 React Development 服务器正在运行

157.230.176.243:3001

我的 CakePHP API 在同一台服务器上提供服务,

157.230.176.243

React 不喜欢我将 API 的完整 URL 传递给fetch()

称呼。我将我的 React 代码切换到

url: "/users/register.json" 它工作正常。

于 2019-03-24T21:39:34.173 回答