英文:
Laravel route group won't return data in API
问题
如果我使用Laravel默认的API路由来获取已登录用户的信息,它可以正常工作:
代码
Route::middleware('auth:api')->get('/auth/user', function (Request $request) {
return $request->user();
});
但是如果我将它移到我的控制器并将路由放在组下面,就不起作用了:
代码
Route::group(['prefix' => 'auth', 'middleware' => ['auth:api', 'cors']], function(){
Route::get('/user', 'API\AuthController@user');
Route::post('/logout', 'API\AuthController@logout');
});
控制器
namespace App\Http\Controllers\API;
....
class AuthController extends Controller
{
public function user(Request $request)
{
$user = $request->user();
return response()->json($user);
}
}
为什么会这样?
英文:
If I use laravel default api route to get my logged user info it works fine:
Code
Route::middleware('auth:api')->get('/auth/user', function (Request $request) {
return $request->user();
});
But if I move it to my controller and place the route under group it doesn't
Code
Route::group(['prefix' => 'auth', 'middleware' => ['auth:api', 'cors']], function(){
Route::get('/user', 'API\AuthController@user');
Route::post('/logout', 'API\AuthController@logout');
});
Controller
namespace App\Http\Controllers\API;
....
class AuthController extends Controller
{
public function user(Request $request)
{
$user = $request->user();
return response()->json($user);
}
}
Why is that?
答案1
得分: 0
已解决
我将我的路由从群组中移除,并且还将我的身份验证路由移到了 api.php
文件的顶部,现在它正常工作。
最终路由:
Route::get('auth/user', 'API\AuthController@user')->middleware(['auth:api', 'cors']);
希望对其他人有所帮助。
英文:
Solved
I took out my route from group and ALSO moved my authentication routes at the top of api.php
file now it's working fine.
Final route:
Route::get('auth/user', 'API\AuthController@user')->middleware(['auth:api', 'cors']);
Hope it help others.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论