如何使用 axios 将身份验证 header 发送到 laravel sanctum

How to send authentication header to laravel sanctum with axios

您好,我正在使用 laravel sanctum (laravel 9),我想使用令牌访问需要身份验证的路由组。然而,我使用分布式应用程序架构 laravel 作为 back-end 框架和一个独立的客户端。我想访问以下路由组:

Route::group(['middleware' => ['auth:sanctum']], function() {
  Route::get('/templates', [TemplateController::class, 'index']);
});
在客户端,我使用 axios 发送 http-requests。客户端已经拥有一个令牌,我尝试使用 get 请求发送它:

import axios from "axios"
const basePath = "http://localhost:8000/api/"
const token = localStorage.getItem('test_token')
const headers = {headers :{ Authorization: `Bearer ${token}` }};
axios.get(basePath+'templates',headers)
  .then(resp => {console.log(resp)})
此方法基于以下 post :How to send authorization header with axios

但是,这会导致状态 401 出现以下默认的未授权错误:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

有谁知道如何将令牌发送到 laravel sanctum 以便中间件可以检测到它? 提前致谢。

您好,我找到了答案,我需要做的就是在 headers 中添加一个接受 属性,如下所示:

const headers = {headers :
                  { Authorization: `Bearer ${token}`,
                    Accept :'application/json', 
                  }
                 };