为什么我的API调用在我的本地服务器上工作而不是在线?(错误500)



我有两个不同的网站(两个不同的域名)使用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']);
});

ApiController:

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);
}

我必须从我的第二个网站调用这些api(我将在这里调用request.com)。我想在线部署这个(planethoster服务器)。我成功地部署了它,但我的页面,我从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"));

我习惯于在JS上调用API与fetch(Ajax),但不与PHP…

为什么它在本地工作,而不是在线?

您可以从您的网络外部连接到您的本地服务器,只有当它有公共访问(开放TCP/IP端口和公共IP)。

http://111.111.1.111

是本例中的本地IP地址。你可以将你的API服务部署到另一台服务器上,然后两者就可以连接了。

最新更新