gpt4 book ai didi

php - 中间件 auth 将 api 路由重定向到/home

转载 作者:行者123 更新时间:2023-12-04 15:49:20 25 4
gpt4 key购买 nike

我创建了 api 路由:

文件 routes/api.php:

Route::middleware('auth:api')->get('/user', 
function (Request $request) {
return $request->user();
});

Route::middleware('auth:api')->group(function()
{
Route::get('/tasks','TaskController@index');
});

之后我转到/api/tasks,中间件重定向到/home,我应该如何使用/api/tasks而不重定向到/home(我已登录),还有我可以使用这个中间件吗?

拉拉维尔 5.5

最佳答案

当路由放置在 api.php 中时,如果您通过 session 登录到网站,它将不起作用。实际上,它会寻找您现在不发送的 API token 。

If you're logged in via a session on the website, just hitting the API endpoint isn't in your browser won't work. It won't be checking the session to see if you're logged in, it will be looking for an API token with the request. Since you aren't specifying a token, this throws an AuthenticationException.

The exception handler then takes this exception, checks your request and sees that it hasn't specified in the headers that it expects JSON. If it was expecting JSON, you would see a JSON response saying unauthenticated. Since it isn't expecting JSON, it redirects to the login page, which redirects to /home since you are logged in via a session. Confusing, but I expect that's the reason.

You'll need to use a tool like Postman if you want to play with your API endpoints so you can specify the required headers in the request.

有关更多详细信息,请访问 here

关于php - 中间件 auth 将 api 路由重定向到/home,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54548154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com