简体   繁体   English

Axios 标头不起作用 Laravel 和 Vue.js

[英]Axios header doesn't work Laravel and Vue.js

I'm using Laravel's Sanctum library to authenticate my API, but it just doesn't work and everything seems on purpose.我正在使用 Laravel 的 Sanctum 库来验证我的 API,但它不起作用,而且一切似乎都是故意的。

I'm creating a token after someone authenticates, and it goes into personal_access_token table in database.我在某人进行身份验证后创建一个令牌,它进入数据库中的personal_access_token表。 And then I insert the token into metatag.然后我将令牌插入元标记。 Then I retrieve the content of the metatag with default javascript (it works) and set it as global authorization header to Axios in bootstrap.js file.然后我使用默认的 javascript(它有效)检索元标记的内容,并将其设置为bootstrap.js文件中 Axios 的全局授权标头。

When using the decrypted bearer token, this approach was working.使用解密的不记名令牌时,此方法有效。 But when I started to use the default token column on personal_access_token , it doesn't work.但是当我开始在personal_access_token上使用默认令牌列时,它不起作用。

The way I define my token我定义令牌的方式

protected function authenticated(Request $request, $user)
    {
        $user->access_token = $user->createToken('api-token')->plainTextToken;

        return $request->wantsJson() ? response()->json($user, 200) : redirect()->intended('/students');
    }

That works good.这很好用。 It inserts new token after someone authenticates.在有人进行身份验证后,它会插入新令牌。

The way I set token as content of metatag我将令牌设置为元标记内容的方式

<meta name="access-token" content="{{auth()->user()->tokens()->first()->token}}" />

I can see the token when I inspect, it is like this: fd34a554cc5a6f14004f8728735375f980d81053b97f719be5bd504647d786cf我检查的时候可以看到token,是这样的: fd34a554cc5a6f14004f8728735375f980d81053b97f719be5bd504647d786cf

The way I set the token as global header to Axios我将令牌设置为 Axios 的全局标头的方式

let metatag = document.querySelector('meta[name="access-token"]').content;

window.axios = require('axios');

axios.defaults.headers.common['Authorization'] = `Bearer ${metatag}`;

There were no problem with that, until I switched to personal_access_table .没有问题,直到我切换到personal_access_table That approach was working when I used a token like 6|yqbI... .当我使用像6|yqbI...这样的令牌时,这种方法有效。

That is returning a 401 error right now, when I click to that I can see my token like Authorization: Bearer fd34a554cc5a6f14004f8728735375f980d81053b97f719be5bd504647d786cf in Request Headers现在返回 401 错误,当我点击它时,我可以看到我的令牌,如Authorization: Bearer fd34a554cc5a6f14004f8728735375f980d81053b97f719be5bd504647d786cf in Request Headers

When I use the hashed token as global header I got error.当我使用散列令牌作为全局标头时,出现错误。

But I've added this line to .env file SANCTUM_STATEFUL_DOMAINS=localhost:8000但我已将此行添加到 .env 文件SANCTUM_STATEFUL_DOMAINS=localhost:8000

Since my localhost has a port, I needed to define it manually in .env file由于我的本地主机有一个端口,我需要在 .env 文件中手动定义它

That solution worked for me.该解决方案对我有用。

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

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