[英]404 Error when using SLIM framework routing
我在http://www.example.com/API/
有我的 SLIM PHP 應用程序
我的index.php
有路由,如下所示:
$app->get('/getstudents', function() use($app) {
$db = new DbHandler();
$result = $db->getAllStudents();
if ($result === false) {
echo "Failed to fetch";
} else {
echo json_encode($result);
}
});
$app->run();
當我使用curl http://example.com/API/getstudents
嘗試 url 時,我收到錯誤在此服務器上找不到請求的 URL /API/getstudents。
如果我使用curl http://example.com/API/index.php/getstudents
,則會按預期返回學生列表。 我在谷歌上搜索並了解到這可能是因為.htaccess
文件和/或虛擬主機設置。
所以我將.htaccess
從API/vendor/slim/slim/.htaccess
復制到 API 文件夾,因此它與index.php
位於同一文件夾中。 在這個文件中,我有:
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteEngine On
RewriteBase /API/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
沒有運氣。 我是否需要同時更改 API 目錄和 API/vendor/slim/slim/ 中.htaccess
文件的內容?
我也不完全確定我需要對我的虛擬主機文件做什么。 在 /etc/apache2/sites-available 我正在編輯example.com.conf ,內容是:
<VirtualHost *:80>
# Admin email, Server Name (domain name), and any aliases
ServerAdmin webmaster@example.co
ServerName www.example.co
ServerAlias example.co
# Index file and Document Root (where the public files are located)
DirectoryIndex index.html index.php
DocumentRoot /var/www/html/example.co/public_html
# Log file locations
LogLevel warn
ErrorLog /var/www/html/example.co/logs/error.log
CustomLog /var/www/html/example.co/logs/access.log combined
<Directory "/var/www/html/example.co/public_html">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
有人可以給我一些關於我在這里可能做錯的指示嗎? 謝謝!
$app->get('/API/getstudents', function() use($app) {
解決這個問題,讓你的路線是這樣的:
$app->get('/api/book', function () {
header('Content-Type: application/json; charset=utf-8');
$data = Book::getBookObjects();
echo $data;
});
這是我的一個項目的示例,您可以使用 API 而不是 api。
.htaccess 文件:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
我的項目的工作樹是這樣的:
Project Folder -> public -> .htaccess, index.php
Project Folder -> api -> book
$app->get('/api/getstudents', function() use($app) {
$db = new DbHandler();
$result = $db->getAllStudents();
if ($result === false) {
echo "Failed to fetch";
} else {
echo json_encode($result);
}
});
$app->run();
嘗試在 API 位置創建.htaccess
文件,其中包含數據的 index.php 文件
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
正如 Slim 論壇上的這個答案所述:
如果您的 Slim 應用程序不在服務器根路徑 ( http://<host>/[index.php]
) 上,則必須說明您的路由的完整路徑。
讓我們以這個 url 為例: http://<host>/staging/
。
您有兩種選擇來實現我們的目標:
$app->get('/staging/', handler);
等等,或$app->SetBasePath('/staging');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.