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));
}
CodePudding user response:
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(...)
CodePudding user response:
you can use axios configs.
for example, import axios :
window.axios = require('axios');
then you can use this:
axios.defaults.headers.common['Authorization'] = "Bearer ...";
you can store your token inside localStorage and use it here.
another way is to use axios interceptors. you read the document about the interceptors here.
