Laravel路由组在API中不会返回数据。

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月4日 12:38:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定