简体   繁体   English

Laravel 5.4 Api Route 401

[英]Laravel 5.4 Api Route 401

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 dev控制台出现了这个错误:

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. 我想我有点不认识,但我不知道如何以这种方式实现。

It doesn't work because your route is protected by auth:api , which returns 401 unauthorized . 它不起作用,因为您的路由受auth:api保护,它返回401 unauthorized The only way to go through auth:api is to send your authentication token with every single request 通过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添加到users表的最简单的解决方案。

If you are going for the cheapest solution, you can follow this post: https://gistlog.co/JacobBennett/090369fbab0b31130b51 如果你想找到最便宜的解决方案,你可以关注这篇文章: https//gistlog.co/JacobBennett/090369fbab0b31130b51

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM