Home > Mobile >  How to send authentication header to laravel sanctum with axios
How to send authentication header to laravel sanctum with axios

Time:04-18

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.

CodePudding user response:

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', 
                  }
                 };

  • Related