Robin Singh
Robin Singh

Reputation: 1796

How to solve Cannot read property 'defaults' of undefined in vue?

I am setting default headers in my vue application, but when I load the app it show me error.

main.js?56d7:14 Uncaught TypeError: Cannot read property 'defaults' of undefined

enter image description here

Code

const token = sessionStorage.getItem("token");
if (token) {
  Vue.prototype.$http.defaults.header.common["Authorization"] = token;
}

Upvotes: 0

Views: 2848

Answers (1)

plsdev89
plsdev89

Reputation: 732

I made a working codepen based on your issue. In your case, you need to create axios client. Please check this codepen. https://codepen.io/plsdev89/pen/VwaPGzr

let apiClient = axios.create({
   baseURL: "https://jsonplaceholder.typicode.com",
   headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
   }
})

const token = "testtoken";
if (token) {
   apiClient.defaults.headers.common["Authorization"] = token;  
}

Vue.prototype.$http = apiClient;

Upvotes: 1

Related Questions