I'm new with VueJs, I'm finding best way to config Global Headers for Get, Post, Patch in VueJS, which is easy to use and strong security. In the current I just write it in export default {}
for every components and it's very bad I know. So I ask you guys to help.
Fixed Thanks to @Hardik Satasiya
~/plugins/axios.js
Every Components:
import axios from 'axios'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
headers: {'Authorization': 'JWT ' + store.state.token}
})
export default api
Issues: Can't tranmit store in to axios.create, so store is not defined
Yes its good idea to use axios
because its repo is maintained.
you can use global config for this
import axios from 'axios';
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
OR best way is to create separate
instances
for this (if you are usingmultiple api
at same time)
import axios from 'axios';
var myApi = axios.create({
baseURL: 'https://my-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'CustomHeader1'}
});
// another api service
var amazonApi = axios.create({
baseURL: 'https://amazon-domain.com/api/',
timeout: 2000,
headers: {'X-Custom-Header': 'CustomHeader2'}
});
export default {
myApi,
amazonApi
}
so you can use api
separately without any conflict.
if you are setting auth header it's nice to not set it at instance creation instead you can set it in your
ready callback
so you can either fetch fromlocalStorage
or obtain from the third party and you can set it.
to change header afterward after creation
myApi.defaults.headers.authorization = 'JWT ' + yourToken;
so you can set header from any part when you are sure you have token then you can use this code to set header. And if you have header already from begging you can also use this code to set it.
ON YOUR MAIN.JS
import axios from "axios";
const base = axios.create({
baseURL: "http://127.0.0.1:8000/",
});
Vue.prototype.$http = base;
Vue.prototype.$http.interceptors.request.use(
config => {
let accessToken = localStorage.getItem('token');
if (accessToken) {
config.headers = Object.assign({
Authorization: `Bearer ${accessToken}`
}, config.headers);
}
return config;
},
error => {
return Promise.reject(error);
}
);
You can use vue-resource
for making http requests and then use interceptors
to modify/patch requests.
Vue.http.interceptors.push(function(request, next) {
// modify method
request.method = 'POST';
// modify headers
request.headers.set('X-CSRF-TOKEN', 'TOKEN');
request.headers.set('Authorization', 'Bearer TOKEN');
// continue to next interceptor
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With