我的路线/ api.php中有以下几行
Route::middleware('api')->get('/posts', function (Request $request) {
Route::resource('posts','ApiControllers\PostsApiController');
});
当我点击http:// localhost:8000 / api / posts时,它会返回空白,但当我将上述路由移动到routes / web.php时,如下所示:
Route::group(['prefix' => 'api/v1'],function(){
Route::resource('posts','ApiControllers\PostsApiController');
});
有用.
作为提醒我已经使用php artisan route清除了路由缓存文件:clear并且我的路由列表附带了php artisan route:list当我的routes / web.php为空且路由/ api.php具有上述路由时:
+--------+----------+-------------+------+---------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-------------+------+---------+------------+
| | GET|HEAD | api/posts | | Closure | api |
+--------+----------+-------------+------+---------+------------+
请注意,对于Web路由部分,列表可以正常工作.
我在这做错了什么?
解决方法:
不要使用中间件api并查看API路由的以下路由示例
示例1(在您的api.php中)
Route::get('test',function(){
return response([1,2,3,4],200);
});
访问此路线为
localhost/api/test
示例2(如果您需要api身份验证,使用laravel passport的基于令牌的身份验证)
Route::get('user', function (Request $request) {
///// controller
})->middleware('auth:api');
您可以获取此路由的请求,但您需要传递访问令牌,因为已使用auth:api中间件.
注意:请参阅/app/http/kernel.php
你可以找到
protected $routeMiddleware = [
//available route middlewares
]
除非你创建一个路由,否则这个文件(kernel.php)中不得有这样的(api)类型的中间件,这就是为什么你不能将中间件用作api的原因.
在这里,我如何创建REST API(api.php)
//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
return response([1,2,3,4],200);
});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
Route::get('user-list',"Api\ApiController@getUserList");
Route::post('send-fax', [
'uses'=>'api\ApiController@sendFax',
'as'=>'send-fax'
]);
Route::post('user/change-password', [
'uses'=>'api\ApiController@changePassword',
'as'=>'user/change-password'
]);
});