为啥我有 TypeError: Cannot read property 'protocol' of undefined using axios with vue?

Posted

技术标签:

【中文标题】为啥我有 TypeError: Cannot read property \'protocol\' of undefined using axios with vue?【英文标题】:Why do I have TypeError: Cannot read property 'protocol' of undefined using axios with vue?为什么我有 TypeError: Cannot read property 'protocol' of undefined using axios with vue? 【发布时间】:2020-08-04 02:54:49 【问题描述】:

我正在尝试使用 axios 向我的后端服务器发出一个简单的 get 请求。我在控制台中得到了这个堆栈跟踪:

TypeError: Cannot read property 'protocol' of undefined
    at isURLSameOrigin (isURLSameOrigin.js?3934:57)
    at dispatchXhrRequest (xhr.js?b50d:109)
    at new Promise (<anonymous>)
    at xhrAdapter (xhr.js?b50d:12)
    at dispatchRequest (dispatchRequest.js?5270:52)

这里是代码文件:https://gist.github.com/DavidMarcu/68f6bd20fa1e21568464f10e2a2baa6a 代码: 存储/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import bookService from '@/service/BookService.js';

Vue.use(Vuex)

export default new Vuex.Store(
  state: 
    books: []
  ,
  mutations: 
    SET_BOOKS(books) 
      this.state.books = books
    
  ,
  actions: 
    fetchBooks(context) 
      bookService.getAllBooks()
        .then(response => 
          console.log(response)
          context.commit('SET_BOOKS', response.data)
      )
        .catch(error => 
          console.log(error)
        )
    
  ,
  modules: 
  
)

Home.vue(视图组件) - 模板无关

<script>
import BookElement from "@/components/BookElement.vue";
export default 
  components: 
    BookElement
  ,
  created() 
    this.$store.dispatch("fetchBooks");
  ,
  computed: 
    books() 
      return this.$store.state.books;
    
  
;
</script>

<style scoped>
</style>

BookService.js


import axios from 'axios';

const apiClient = axios.create(
  baseUrl: `http://localhost:9001/books`,
  headers: 
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  
)

const bookService = 
  getAllBooks() 
    return apiClient.get()
  


export default bookService

我尝试了插件解决方案(vue-axios),但我不明白仅仅为了发出一个甚至不在 .vue 文件中而是在我导入到我的 .js 文件中的 get 请求的所有麻烦零件。确实安装了 axios 包。我期望在 vue devtools 的 Home 组件中看到 books 计算属性中我有响应正文。

编辑:我也在问题中添加了代码。

【问题讨论】:

请添加您的代码。我无法访问github链接。 我现在公开了要点。我的错,对不起。 【参考方案1】:

您没有将网址传递给get

改成这样:

return apiClient.get('/')

【讨论】:

以上是关于为啥我有 TypeError: Cannot read property 'protocol' of undefined using axios with vue?的主要内容,如果未能解决你的问题,请参考以下文章

TypeError: Cannot read properties of undefined (reading 'length') - 想要解释为啥代码这样说

× TypeError: Cannot read properties of undefined (reading 'getState')

js为啥会报错Uncaught TypeError: Cannot read property 'style' of undefined?

为啥 Uncaught TypeError: Cannot set property 'innerHTML' of null 显示即使 <span> 和 js 中的 id 相同? [复制]

TypeError: cannot use a string pattern on a bytes-like object

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) JavaScript