【发布时间】:2015-03-31 23:19:53
【问题描述】:
对于其中一个项目,我正在使用 Slim Framework http://www.slimframework.com/ 在 PHP 中创建 restful API。
我使用https://github.com/slimphp/Slim 处的说明将框架复制到 PHP 项目文件夹中,手动安装了该框架。
后来我也更新了我的 .htaccess。
对于我的项目,我有以下目录结构
project\
----slim\
----tests\
----index.php
----.htaccess
为此,Get 调用,即http://someIp/project/ 对我有用。它获取标准的“欢迎使用 Slim!恭喜!您的 Slim 应用程序正在运行。如果这是您第一次使用 Slim,请从这个“Hello World”教程开始。” 但是,post/patch/delete 和其他 get 不起作用。甚至没有打招呼。它给出了未找到的错误。
http://someIp/project/hello/:name 在此服务器上找不到请求的 URL /project/hello/:name。
http://someIp/project/post 在此服务器上找不到请求的 URL /project/post。
将我的 .htaccess 文件更新为:
RewriteEngine On
RewriteBase /project/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
还是失败了。
当我将 apache 配置文件更改为 allowOverride = all 时,即使对 index.php 的 GET 调用也失败了。当然,它不是从 .htaccess 映射的。
我仍然不知道需要对 .htaccess 或任何其他文件进行哪些更改才能使其正常工作。
代码如下:
\Slim\Slim::registerAutoloader();
/**
* Step 2: Instantiate a Slim application
*
* This example instantiates a Slim application using
* its default settings. However, you will usually configure
* your Slim application now by passing an associative array
* of setting names and values into the application constructor.
*/
$app = new \Slim\Slim();
/**
* Step 3: Define the Slim application routes
*
* Here we define several Slim application routes that respond
* to appropriate HTTP request methods. In this example, the second
* argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete`
* is an anonymous function.
*/
// GET route
$app->get(
'/',
function () {
$template = "hi";
echo $template;
}
);
//$app->get(
// '/v1/status/',
// function() {
// echo "status";
// }
//);
//
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
// POST route
$app->post(
'/post',
function () {
echo 'This is a POST route';
}
);
// PUT route
$app->put(
'/put',
function () {
echo 'This is a PUT route';
}
);
// PATCH route
$app->patch('/patch', function () {
echo 'This is a PATCH route';
});
// DELETE route
$app->delete(
'/delete',
function () {
echo 'This is a DELETE route';
}
);
/**
* Step 4: Run the Slim application
*
* This method should be called last. This executes the Slim application
* and returns the HTTP response to the HTTP client.
*/
$app->run();
【问题讨论】:
-
你真的在 index.php 中定义了路由吗?
-
我在 index.php 中有默认路由,但它们似乎不起作用
-
你是否将 $app->run() 添加到 index.php 的末尾?这是我经常犯的错误:)
-
@Tuim 它已经在那里了.. 我正在使用他们为 Hello 提供的现有代码
-
readme 中的 hello world 示例只定义了一个 GET 路由。它没有定义任何 POST 或 PUT 路由。请在您的问题中包含您使用的代码,我们可以理解您使用的代码。
标签: php .htaccess api rest slim