我有兩個使用 laravel 的不同網站(兩個不同的域)。其中一個(我將在此處稱為 api.com)提供具有不同路由的 api,并且實際上位于本地服務器 (111.111.1.111) 上:
路線/api.php:
Route::prefix('news')->group(function () {
Route::get('', [ApiController::class, 'newsIndex']);
Route::get('{id}', [ApiController::class, 'newsShow']);
});
介面控制器:
public function newsIndex()
{
$news = News::orderByDesc('ordre')
->where('site_destination', 'like', '%other%')
->where('statut', '=', 1)
->get();
return response()->json($news);
}
public function newsShow($id)
{
$news = News::findOrfail($id);
return response()->json($news);
}
我必須從我的第二個網站(我將在此處呼叫 request.com)呼叫這些 API。我想在線部署這個(行星服務器)。我成功部署了它,但是我從 api.com 呼叫 API 的頁面不起作用:回傳 500 錯誤。
在 request.com 上進入我的控制器:
public function index()
{
$newsListFromApi = json_decode(file_get_contents("http://111.111.1.111/api/news"));
$newsFirstPictureList = [];
foreach ($newsListFromApi as $key => $value) {
$newsFirstPictureList[$value->id] = json_decode(file_get_contents("http://111.111.1.111/api/news/" . $value->id . "/firstPicture"));
}
return View::make('client.news.index', [
'newsListFromApi' => $newsListFromApi,
'newsFirstPictureList' => $newsFirstPictureList,
]);
}
public function show($newsId)
{
$news = json_decode(file_get_contents("http://111.111.111/api/news/" . $newsId));
$newsDocs = json_decode(file_get_contents("http://111.111.1.111/api/news/" . $newsId . "/docs"));
// dump($newsDocs);
return View::make('client.news.show', [
'news' => $news,
'newsDocs' => $newsDocs,
]);
}
如果 request.com 在本地主機(生產或開發模式)上,它作業正常。我在控制臺中只有關于我知道的混合內容的警告訊息。但是如果我部署 request.com 我有一個 500 錯誤。
在日志上我有這個條目:
*[2022-06-13 13:55:03] production.ERROR: file_get_contents(http://111.111.1.111/api/news): failed to open stream: Connection timed out {"userId":x,"email":"xx","exception":"[object] (ErrorException(code: 0): file_get_contents(http://111.111.1.111/api/news): failed to open stream: Connection timed out at /home/xx/laravel/releases/20220613-120400/app/Http/Controllers/Client/NewsController.php:12)
[stacktrace]
api.com 和 request.com api 不在同一臺服務器上進行開發。
您認為這可能是由混合內容錯誤引起的嗎?我認為瀏覽器只會不顯示影像,但無論如何都會顯示頁面......
另外我認為這可能是一個跨源問題,但我沒有這樣的錯誤訊息。
我想,多虧了日志,當我呼叫 API 時,這行代碼有問題:
$newsListFromApi = json_decode(file_get_contents("http://111.111.1.111/api/news"));
我習慣于使用 fetch(Ajax) 在 JS 上呼叫 API,但不使用 PHP ......
為什么它可以在本地作業,但不能在線?
uj5u.com熱心網友回復:
只有當它具有公共訪問權限(打開 TCP/IP 埠和公共 IP)時,您才能從網路外部連接到本地服務器。http://111.111.1.111在此背景關系中是本地 IP 地址。
您可以將您的 API 服務部署到另一臺服務器,然后兩者就可以連接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490514.html
標籤:php 拉拉维尔 api 部署 http-status-code-500
