我使用 React 作為前端并使用它設定 PHP 后端。
通過將這個 React 專案放在 XAMPP 內的 htdocs 檔案夾中,我成功地連接了兩者。
當我向以下 URL 發出請求時
useEffect(() => {
fetch("http://localhost:80/php_w_r/api/index.php?url=Users/index", {
method: 'GET',
}).then((res) => res.json())
.then((data) => {
console.log(data)
}).catch(err => console.log(err))
})
好訊息是它可以作業,我取回了一個物件。這是我的 PHP 代碼。
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
class Users extends Controller
{
public function __construct()
{
$this->userModel = $this->model('User');
}
public function index() {
$s = $this->userModel->login();
$json_data = json_encode((array) $s);
print_r($json_data);
}
}
我遇到的真正痛苦是在 PHP 方面出現問題時進行除錯。我能夠解決這個問題的方法是打開開發者控制臺。
我不斷收到錯誤訊息:
Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0
Is there any way I can make development easier without having to open up the console every time I think there is something wrong with the PHP code ? Even when there is something wrong, I don't receive a very helpful message as to why things might be wrong on the PHP side of things. The only message I receive is
Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0
Before I was able to see any errors coming from PHP in my views directory. Because I am now using React those errors no longer appear.
I am taking setting up my backend from this tutorial on Udemy.
https://www.udemy.com/course/object-oriented-php-mvc/
uj5u.com熱心網友回復:
你可以
- 將 PHP 中的任何除錯資訊(例如 print_r 輸出)記錄到檔案中,而不是輸出它。還要確保關閉 PHP 的螢屏錯誤報告,并打開記錄到檔案的錯誤。
和/或
- 使用瀏覽器開發人員工具中的網路工具檢查從服務器回傳的每個請求的原始回應,因此您不必擔心 JSON 決議錯誤。
PS 不要使用像print_r正常輸出這樣的工具——它是作為除錯工具使用的,可能會添加你意想不到的額外內容。只需使用echo或print用于常規輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360468.html
標籤:php reactjs debugging error-handling
