最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to send authentication header to laravel sanctum with axios - Stack Overflow

programmeradmin1浏览0评论

Hi I was working with laravel sanctum (laravel 9) and I wanted to use a token to access a route group that required authentication. I however use a distributed application architecture with laravel as back-end framework and an independent client. I wanted to access the following route group :

Route::group(['middleware' => ['auth:sanctum']], function() {
  Route::get('/templates', [TemplateController::class, 'index']);
});

Hi I was working with laravel sanctum (laravel 9) and I wanted to use a token to access a route group that required authentication. I however use a distributed application architecture with laravel as back-end framework and an independent client. I wanted to access the following route group :

Route::group(['middleware' => ['auth:sanctum']], function() {
  Route::get('/templates', [TemplateController::class, 'index']);
});
On the client side I use axios to send http-requests. The client was already in possession of a token I tried sending it with the get request :

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)})
This approach was based on the following post : How to send authorization header with axios

This however resulted in a status 401 with the following default unauthorized error :

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

Does anyone know how to send a token to laravel sanctum so the middleware can detect it? Thanks in advance.

Share Improve this question asked Apr 15, 2022 at 9:32 Jip HelsenJip Helsen 1,3665 gold badges20 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Hi I found the answer all I needed to do is add an accept property in the headers like this :

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

发布评论

评论列表(0)

  1. 暂无评论