【发布时间】:2015-10-14 20:03:13
【问题描述】:
我正在创建一个只能通过 POST 使用的 API。我计划拥有多个版本的 API,因此当前版本使用 v1 作为 URL 的一部分。
现在,如果通过 GET、PUT 或 DELETE 进行 API 调用,我想返回一个失败响应。为此,我使用Route::match(),它工作在下面的代码中非常好:
Route::group(['namespace'=>'API', 'prefix' => 'api/v1', 'middleware' => 'api.v1'], function() {
Route::match(['get', 'put', 'delete'], '*', function () {
return Response::json(array(
'status' => 'Fail',
'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
));
});
// User
Route::post('user/create', array('uses' => 'APIv1@createUser'));
Route::post('user/read', array('uses' => 'APIv1@readUser'));
// other calls
// University
Route::post('university/create', array('uses' => 'APIv1@createUniversity'));
Route::post('university/read', array('uses' => 'APIv1@readUniversity'));
// other calls...
});
但是,我注意到我可以对路由进行更多分组,以分离 API 版本和对特定实体的调用,例如 user 和 university:
Route::group(['namespace'=>'API', 'prefix' => 'api'], function() {
Route::match(['get', 'put', 'delete'], '*', function () {
return Response::json(array(
'status' => 'Fail',
'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
));
});
/**
* v.1
*/
Route::group(['prefix' => 'v1', 'middleware' => 'api.v1'], function() {
// User
Route::group(['prefix' => 'user'], function() {
Route::post('create', array('uses' => 'APIv1@createUser'));
Route::post('read', array('uses' => 'APIv1@readUser'));
});
// University
Route::group(['prefix' => 'university'], function() {
Route::post('create', array('uses' => 'APIv1@createUniversity'));
Route::post('read/synonym', array('uses' => 'APIv1@readUniversity'));
});
});
});
上面代码中的Route::match()不起作用。当我尝试使用例如访问任何 API 调用时GET,匹配被忽略,我得到 MethodNotAllowedHttpException。
我可以让第二个路由结构再次与Route::match() 一起工作吗?我已经试着把它放在组中的任何地方。将Route::match() 放在孔结构之外并将路径设置为“api/v1/*”也可以。
【问题讨论】: