【问题标题】: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链接。
  • 我现在公开了要点。我的错,对不起。

标签: vue.js axios vuex


【解决方案1】:

您没有将网址传递给get:

改成这样:

return apiClient.get('/')

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2021-09-25
    • 2019-01-11
    • 2019-08-13
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多