使用Laravel默认vuejs设置401(未授权)

时间:2017-03-22 09:36:11

标签: php laravel vue.js axios

我尝试使用axios从vuejs访问laravel api时获得401。 这是Laravel 5.4开箱即用的设置,所以我不知道它为什么不起作用。

这是我的代码:

// routes -> api.php

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

// axios request

axios.get('/api/user').then(function (response) {
    console.log(response);
    console.log(response.status);
});

请求包含所有令牌内容..我认为。

X-CSRF-TOKEN:uAW2t..
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI..

所有响应请求:

General
Request URL:http://localhost/public/api/user
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:80
Response Headers
view source
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Length:28
Content-Type:application/json
Date:Wed, 22 Mar 2017 09:35:49 GMT
Keep-Alive:timeout=5, max=92
Server:Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By:PHP/5.6.25
X-RateLimit-Limit:60
X-RateLimit-Remaining:57
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:XSRF-TOKEN=eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0%3D; laravel_session=eyJpdiI6IkhcLzJKRDVDTHRDN1FWUjZicDdZaVJnPT0iLCJ2YWx1ZSI6IlJoTkVQWUQ5OWZuYUo4bmF1eHRMYWFlamZramhtTkpmMnYwbUlaaTV3ZENuWFJQZW9IcDZxbU5EQjJXSDY2a01WMHpjeHU3Uk9UOG44MzN3NmgxK2NBPT0iLCJtYWMiOiI4OWM1ZWI3YjIzMDg5MTAwYjc0YmZmZDE4OTY3MjU5OTNkZDdjYjY2MjU3NmFlNTE3NDE2NTVjYzBhY2Y4MzJmIn0%3D
DNT:1
Host:localhost
Referer:http://localhost/public/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-CSRF-TOKEN:uAW2tI8bags0CaQaYBKmbfdExoCVDnZlJb1sW9f4
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0=

2 个答案:

答案 0 :(得分:0)

如果您授权用户使用api,则必须在url或授权标头密钥中添加令牌。该令牌应来自api_token表中的users列。

var token = 'exampleToken';
axios.get(
    '/api/user?api_token=' + token, // here 
    { 
        headers:
            {
                'Authorization':'Bearer ' + token // or here
            }
    }
).then(...)

答案 1 :(得分:-1)

axios.get('/api/user',{headers:{
     'Accept':'application/json',
     'Authorization':'Bearer ' + window.localStorage.getItem('token_name_here')
     'cache-control':'no-cache'
}).then(...)...