Monday, February 21, 2022

[FIXED] Send Sanctum token automaticaly

Issue

I'm working on a Laravel 8 Project with Sanctum and VueJs, and I would like to know if there is any way to send the token without write each time header in my axios request:

const token = localStorage.getItem("token");
        axios
            .get("/api/endpoint/", {
                headers: {
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + token
                }
            })
            .then(response => (this.expenses = response.data));
    }

Solution

Define axios config in lib or something like this:

import Axios from 'axios'

const axios = Axios.create({
    baseURL: process.env.NEXT_PUBLIC_SERVER_BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        Authorization: "Bearer " + token
    },
})

export default axios

Then use your lib instead of base axios like this:

import axios from '@/lib/axios'

 axios.post(...)
        


Answered By - Ali Raza

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.