Laravel 5.4 Api 路线 401

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43281009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:44:42  来源:igfitidea点击:

Laravel 5.4 Api Route 401

phplaravelapilaravel-5.3laravel-5.4

提问by utdev

I built a new laravel 5.4 project.

我构建了一个新的 Laravel 5.4 项目。

I tried to do the steps below in my api route, but somehow they do not work.

我尝试在我的 api 路由中执行以下步骤,但不知何故它们不起作用。

In my app.js file I have this ajax call:

在我的 app.js 文件中,我有这个 ajax 调用:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    }
});
$.ajax({
    url: 'api/postStream',
    type: 'post',
    data: { imgData: imgData },
    success:function(data) {
        console.log('success');
    }
});

My Api Route looks like this:

我的 Api 路由如下所示:

Route::group(['middleware' => 'auth:api'], function()
{
    Route::post('postStream', ['as' => 'image', 'uses' => 'ApiController@postStream']);
});

And my controller:

还有我的控制器:

public function postStream(Request $request)
{
    $imgData = $request->imgData;
    ...
}

But I get this error in my chrome dev console:

但我在我的 chrome 开发控制台中收到此错误:

POST http://localhost/app/public/api/postStream 401 (Unauthorized)

And in the network tools this:

在网络工具中:

{error: "Unauthenticated."}
error
:
"Unauthenticated."

I guess I am somewhat not authentificated, but I do not know how to make that happen this way.

我想我有点没有经过身份验证,但我不知道如何以这种方式实现。

回答by EddyTheDove

It doesn't work because your route is protected by auth:api, which returns 401 unauthorized. The only way to go through auth:apiis to send your authentication token with every single request

它不起作用,因为您的路线受 保护auth:api,它返回401 unauthorized。唯一的方法auth:api是在每个请求中发送您的身份验证令牌

var token = <?php json_encode(Auth::user()->api_token); ?>; //if you are using api_token

$.ajax({
    url: 'api/postStream',
    headers: {
        'Authorization':'Bearer ' + token,
    },
    type: 'post',
    ...
});

The way you get your token is entirely up to you. You could use Passport or simply the easiest solution which is adding api_token to your users table.

您获得令牌的方式完全取决于您。您可以使用 Passport 或简单的最简单的解决方案,即将 api_token 添加到您的用户表中。

If you are going for the cheapest solution, you can follow this post: https://gistlog.co/JacobBennett/090369fbab0b31130b51

如果您要寻找最便宜的解决方案,可以关注此帖子:https: //gistlog.co/JacobBennett/090369fbab0b31130b51