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 ju
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.