【问题标题】:How to solve Cannot read property 'defaults' of undefined in vue?如何解决无法读取 vue 中未定义的属性“默认值”?
【发布时间】:2020-12-13 00:46:53
【问题描述】:

我在我的 vue 应用程序中设置默认标题,但是当我加载应用程序时它显示错误。

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

代码

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

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    我根据您的问题制作了一个工作代码笔。 在您的情况下,您需要创建 axios 客户端。 请检查此代码笔。 https://codepen.io/endmaster0809/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;
    

    【讨论】:

    • 感谢 @endmaster0809 的这项工作,你拯救了我的一天
    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 2019-04-30
    • 2021-05-10
    • 2021-12-18
    • 1970-01-01
    • 2022-01-26
    • 2019-11-21
    • 2019-01-30
    相关资源
    最近更新 更多