我正在尝试通过 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