首页 > 解决方案 > 如何在使用 vue-cli3 创建的 Vue2 项目中使用 axios

问题描述

vue create axe我使用命令创建了一个新的 vue 项目vue-cli-3.0.016beta。然后使用npm install axios --save. 在main.js我导入的文件axios中,如下所示。

import Vue from 'vue'
import App from './App.vue'

import axios from 'axios'

Vue.config.productionTip = false
Vue.use(axios)

new Vue({
    render: h => h(App)
}).$mount('#app')

除此之外没有任何代码更改。我仍然收到如下错误:

Unhandled promise rejection 
TypeError
​
columnNumber: 7
​
fileName: "http://localhost:8080/app.js line 1065 > eval"
​
lineNumber: 57
​
message: "parsed is undefined"
​
stack: "isURLSameOrigin@webpack-internal:///./node_modules/axios/lib/helpers/isURLSameOrigin.js:57:7\ndispatchXhrRequest@webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:109:50\nPromise@webpack-internal:///./node_modules/core-js/modules/es6.promise.js:177:7\nxhrAdapter@webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:12:10\ndispatchRequest@webpack-internal:///./node_modules/axios/lib/core/dispatchRequest.js:59:10\nrun@webpack-internal:///./node_modules/core-js/modules/es6.promise.js:75:22\nnotify/<@webpack-internal:///./node_modules/core-js/modules/es6.promise.js:92:30\nflush@webpack-internal:///./node_modules/core-js/modules/_microtask.js:18:9\n"
​
__proto__: Object { stack: "", … }

我想全局 axios 使用拦截器,因此在 main.js 中调用它。但是如果我在视图页面中使用它就没有错误!

这是一个错误还是我做错了?请帮助我解决这个问题并在全球范围内使用 axios。

谢谢

标签: vuejs2axios

解决方案


所以我看到的错误就在这里

Vue.use(axios)

Vue.use需要一个 vue 可安装插件。

你可以看看 vue-axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

但我强烈反对它。

最好创建自己的ApiHandler.js文件来分别处理所有远程内容,并且您可以轻松地从任何地方调用,包括 vue 组件和 vuex。

这是我上课的开始

<script>
import axios from 'axios';

class ApiHandler{
  constructor(apiUrl) {
    this.axios = axios;
    this.apiUrl = apiUrl || '';  // this line allow passing a custom endpoint for testing
    this.config = {
      headers: { 'Cache-Control': 'no-cache' },  // can setup to prevent all caching
      baseURL: this.apiUrl,
    };
  }

  /**
   * @param {Object} payload
   * @param {String} payload.username
   * @param {String} payload.password
   */
  login({ username, password }) {
    return new Promise((resolve, reject) => {
      this.axios.post('/api/login', { username: username.toLowerCase(), password }, this.config)
        .then((response) => {
          if (response.code === 200 && response.body && response.body.token) {
            resolve(response.body.token);
          } else {
            reject('Bad Login');
          }
        })
        .catch((err) => {
          reject('internal error');
        });
    });
  }
}
</script>

然后,您可以通过...从任何地方调用它

<script>
  import ApiHandler from '../lib/ApiHandler';
  const apiRequest = new ApiRequest();

  // and then anywhere in the script
  let payload = {
    username:'someuser',
    password:'somepassword',
  };
  apiRequest.login(payload)
    .then(()=>{
      // yay - I'm logged in
    })
    .catch(err => {
      // oh oh, display error
    })
</script>

这为您提供了更大的灵活性,并允许您分离远程操作,并允许将第一站响应处理与您的组件分开,从而实现更多的可重用性。


推荐阅读