Giter Site home page Giter Site logo

imcvampire / vue-axios Goto Github PK

View Code? Open in Web Editor NEW
2.0K 2.0K 183.0 3.02 MB

A small wrapper for integrating axios to Vuejs

Home Page: https://www.npmjs.com/package/vue-axios

License: MIT License

JavaScript 100.00%
axios hacktoberfest integrating-axios vue-axios vuejs wrapper

vue-axios's Introduction

vue-axios

npm version install size npm downloads jsdelivr License

A small wrapper for integrating axios to Vuejs

Why

I created this library because, in the past, I needed a simple solution to migrate from vue-resource to axios.

It only binds axios to the vue instance so you don't have to import everytime you use axios.

How to install:

ES6 Module:

npm install --save axios vue-axios

Import libraries in entry file:

// import Vue from 'vue'   // in Vue 2
import * as Vue from 'vue' // in Vue 3
import axios from 'axios'
import VueAxios from 'vue-axios'

Usage in Vue 2:

Vue.use(VueAxios, axios)

Usage in Vue 3:

const app = Vue.createApp(...)
app.use(VueAxios, axios)

Script:

Just add 3 scripts in order: vue, axios and vue-axios to your document.

Usage:

in Vue 2

This wrapper bind axios to Vue or this if you're using single file component.

You can use axios like this:

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})

in Vue 3

This wrapper bind axios to app instance or this if you're using single file component.

in option API, you can use axios like this:

// App.vue
export default {
  name: 'App',
  methods: {
    getList() {
      this.axios.get(api).then((response) => {
        console.log(response.data)
      })
      // or
      this.$http.get(api).then((response) => {
        console.log(response.data)
      })
    }
  }
}

however, in composition API setup we can't use this, you should use provide API to share the globally instance properties first, then use inject API to inject axios to setup:

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App).use(store)
app.use(VueAxios, axios)
app.provide('axios', app.config.globalProperties.axios)  // provide 'axios'
app.mount('#app')

// App.vue
import { inject } from 'vue'

export default {
  name: 'Comp',
  setup() {
    const axios: any = inject('axios')  // inject axios

    const getList = (): void => {
      axios
        .get(api)
        .then((response: { data: any }) => {
          console.log(response.data)
        });
    };

    return { getList }
  }
}

Please kindly check full documentation of axios too

Multiple axios instances support

The library allows to have different version of axios at the same time as well as change the default registration names (e.g. axios and $http). To use this feature you need to provide options like an object where:

  • <key> is registration name
  • <value> is instance of axios

For Vue it looks like this:

// Vue 2 / Vue 3 + Composition API
import App from './App.vue'
import VueAxios from 'vue-axios'
import axios from 'axios'
import axios2 from 'axios'
Vue.use(VueAxios, { $myHttp: axios, axios2: axios2 }) // or app.use() for Vue 3 Optiona API

// usage
export default {
  methods: {
    getList(){
      this.$myHttp.get(api).then((response) => {
        console.log(response.data)
      })
      this.axios2.get(api).then((response) => {
        console.log(response.data)
      })
    }
  }
}

It works similarly in Options API of Vue 3 but if you want to use Composition API you should adjust your code a bit to extract proper keys, e.g.:

// Vue 2 + Setup function
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App).use(store)
app.use(VueAxios, { $myHttp: axios, axios2: axios2 })
app.provide('$myHttp', app.config.globalProperties.$myHttp)  // provide '$myHttp'
app.provide('axios2', app.config.globalProperties.axios2)  // provide 'axios2'
app.mount('#app')

// App.vue
import { inject } from 'vue'

export default {
  name: 'Comp',
  setup() {
    const $myHttp: any = inject('$myHttp')  // inject $myHttp

    const getListWithMyHttp = (): void => {
      $myHttp
        .get(api)
        .then((response: { data: any }) => {
          console.log(response.data)
        });
    };

    const axios2: any = inject('axios2')  // inject axios2
    const getListWithAxios2 = (): void => {
      axios2
        .get(api)
        .then((response: { data: any }) => {
          console.log(response.data)
        });
    };


    return { getListWithMyHttp, getListWithAxios2 }
  }
}

vue-axios's People

Contributors

alanscut avatar dependabot[bot] avatar dungnx avatar eliamartani avatar evenfrost avatar hotrungnhan avatar imcvampire avatar probil avatar sc0vu avatar xiaofan9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-axios's Issues

Accessing second lvl data?

Hi,

Unsure if this is related to vue-axios or not but here we go:
I am not able to access second lvl data for some reason "Cannot read property ... of undefined"

My code looks like the following:

	data() {
		return {
			project: {}
		}
	},
	beforeRouteEnter (to, from, next) {
 		const api = '/static/data/projects/' + to.params.slug + '.json'

		Vue.axios.get(api).then((response) => {
			next(vm => {
	          vm.project = response.data
	        })
		})
  	},

And the json i'm accessing like this:

{
	"title": "Vogue",
	"hero": "static/img/vogue/vogue-hero.jpg",
	"next": {
		"slug": "pointsbet",
		"thumb": "static/img/pointsbet/pointsbet-hero.jpg",
		"title": "Pointsbet"
	}
}

Any idea? project.title works fine, but not project.next.slug for example.

在使用post发送请求时有10%的几率会发送两次请求

我在开发的过程中遇到了一个问题,当我执行这段代码的时候,他会有5%-10%的几率,额外发送一个options类型的请求。

this.$http.post(this.apiUrl + 'wechat/bind', {
                    appid: this.ruleForm.appid,
                    appsecrect: this.ruleForm.appsecrect
                }).then(response => {

                    console.log(response);

            }, response => {
                    console.log(response);
                });

发生额外请求时,用chrome查看是这样的

General

Request URL:http://localhost/chapiaoling/api/index.php/wechat/bind
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade

Response Headers

HTTP/1.1 200 OK
Date: Sat, 20 May 2017 17:40:18 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: content-type
Access-Control-Request-Method: GET,POST
Content-Length: 101
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

Request Headers

OPTIONS /chapiaoling/api/index.php/wechat/bind HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: /
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: zh-CN,zh;q=0.8

请求时是Access-Control-Request-Method: POST 但chrome的General中显示的请求确是Request Method:OPTIONS,我在服务气端用$_SERVER['REQUEST_METHOD']查看请求方式也是OPTIONS。希望尽快修复此bug。

Can't set global headers.

To use a global header on each Axios request one would normally use something like this:

axios.defaults.headers.common.Authorization = token;
axios.defaults.headers.common['Authorization'] = token;

But this is not working with Vue, at least for me. Trying to set the global token by using either this.axios or Vue.axios gives the same result which is the header not being sent at all. Related to #1 as well.

Any ideas?

Namespace error on /api route

Hi,

I wanted to test your work and got an error in DefaultController at line 91:
$apartments = $em->getRepository('App:Apartment')->findByLimit(10);

I fixed it by changing 'App:Apartment' by 'AppBundleApartment'

Can't get it to work for some reason

Hi,

I am setting up a webapp using Vue and Vue-Auth, and it uses VueAxios to make it work.

However, for some reason, I always get:

vue-axios.min.js?a7fe:1 Uncaught TypeError: Cannot set property 'axios' of undefined
    at o (vue-axios.min.js?a7fe:1)
    at Function.Vue.use (vue.common.dev.js?4650:5098)
    at eval (app.js?6d40:38)
    at Module../resources/js/app.js (app.js:2880)
    at __webpack_require__ (app.js:833)
    at fn (app.js:130)
    at Object.0 (app.js:4183)
    at __webpack_require__ (app.js:833)
    at app.js:971
    at app.js:974

Which is super annoying right now. So, what am I doing wrong?

File app.js (the rest is just basic components):

import './bootstrap'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Axios from 'axios'
import VueAxios from 'vue-axios'
import Vuex from 'vuex'
import VueSweetalert2 from 'vue-sweetalert2'
import VueProgressBar from 'vue-progressbar'
import './registerServiceWorker'
import ArgonDashboard from './plugins/argon-dashboard'

import auth from '@websanova/vue-auth'
import authBearer from '@websanova/vue-auth/drivers/auth/bearer'
import authVueRouter from '@websanova/vue-auth/drivers/router/vue-router.2.x'
import authAxios from '@websanova/vue-auth/drivers/http/axios.1.x'

Vue.config.productionTip = false
Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Axios.defaults.withCredentials = true;

Vue.use(ArgonDashboard)
Vue.use(VueSweetalert2)
Vue.use(VueProgressBar)
Vue.use(Vuex)
Vue.use(VueAxios, Axios)
Vue.use(auth, {
    auth: authBearer,
    http: authAxios,
    router: authVueRouter,
    rolesKey: 'role',
    loginData: {
        method: 'POST',
        redirect: { name: 'dashboard' },
        staySignedIn: true,
        fetchUser: true,
        url: '/api/login'
    },
    logoutData: {
        makeRequest: true,
        redirect: { name: 'login' },
        method: 'POST',
        url: '/api/logout'
    },
    fetchData: {
        enabled: true,
        url: '/api/current-user',
        method: 'GET'
    },
    refreshData: {
        enabled: false
    }
})

new Vue({
    router,
    el: '#app',
    render: h => h(App)
})

/*axios.interceptors.request.use(config => {
    app.$Progress.start(); // for every request start the progress
    return config;
});

axios.interceptors.response.use(response => {
    app.$Progress.finish(); // finish when a response is received
    return response;
});
*/

If anyone has an idea, I'm open!

Axios types appear to be wrong: AxiosInstance vs AxiosStatic

vue-axios/index.d.ts

Lines 2 to 18 in 30998f3

import {AxiosInstance} from "axios";
declare module "vue/types/vue" {
interface Vue {
axios: AxiosInstance;
$http: AxiosInstance;
}
interface VueConstructor {
axios: AxiosInstance;
}
}
declare class VueAxios {
static install: PluginFunction<AxiosInstance>;
}

In the above code, based on local projects, AxiosStatic is the appropriate type here as it provides the static methods, .all .spread etc...

Updating my local node_modules package appears to fix the problem, but maybe someone is aware of a counter reason why AxiosInstance is correct?

直接下下来运行,报20个错误,是我这边环境的问题吗?

(unknown) [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(found in at D:\my_fe\xyy-vue-master\xyy-vue-master\src\components\nav.vue)warn
(unknown) [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(found in at D:\my_fe\xyy-vue-master\xyy-vue-master\src\components\travelList.vue)warn
(unknown) [Vue warn]: Error in render function:
(found in at D:\my_fe\xyy-vue-master\xyy-vue-master\src\components\tabar.vue)warn
(unknown) TypeError: Cannot read property 'path' of undefined(…)handleError
5(unknown) [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(found in at D:\my_fe\xyy-vue-master\xyy-vue-master\src\components\sidebar.vue)warn
(unknown) [Vue warn]: Error in render function:
(found in at D:\my_fe\xyy-vue-master\xyy-vue-master\src\components\tabar.vue)warn
(unknown) TypeError: Cannot read property 'path' of undefined(…)

IsURLSameOrigin error when testing the api locally

As stated on the documentation page, i always configure my main.js file this way

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

However, when trying to hit a local api endpoint (like localhost:8000) it throws the following error and never proceeds the request

Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined at isURLSameOrigin

It can't be a problem with CORS because when I try to use axios.get or the browser fetch API it works fine

NPM audit reports vulnerabilities associated with rollup-babel dependency

Running an NPM audit against vue-axios 3.1.2 gives the following report:

[high] Regular Expression Denial of Service
 - dependencies: vue-axios>rollup-babel>babel-core>minimatch
--------------------------------------------------
[high] Prototype Pollution
 - dependencies: vue-axios>rollup-babel>babel-core>babel-plugin-proto-to-assign>lodash
 - dependencies: vue-axios>rollup-babel>babel-core>lodash

I think there's a couple of issues here:

  1. rollup-babel has been superseded by rollup-plugin-babel, so you should only required the latter (you currently have dependencies on both)
  2. Both rollup-babel and rollup-plugin-babel have been placed under dependencies, when I believe they should be devDependencies

vue-axios 3.1.3 (your latest release at the time of writing) also has this problem, so upgrading isn't a solution. I believe that you'll need to drop rollup-babel and move rollup-plugin-babel to devDependencies, and release a patch.

Cannot instantiate VueAxios

In main.js, I have:

import Vue from "vue";
import VueAxios from "vue-axios";
import axios from "axios";

Vue.use(VueAxios, axios);
// ...

But, I get an error:

vue-axios.min.js?a7fe:1 Uncaught TypeError: Cannot set property 'axios' of undefined

VueAxios version: 3.0.1
Axios version: 0.20.0

Type definition?

Hi,

Thanks for this library. I really appreciate it. Just wonder if you can provide us with type definition, please?

Cheers,

Vue is not defined

當我根據vue-axios指導方式去引用axios時

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})

第一個Vue.axios就失敗顯示error
Vue is not defined

其他兩個沒問題!

有人和我一樣嗎?謝謝

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

How to send CSRF tokens in request headers?

Hi,

I'm using node express as my backend which uses lusca to validate CSRF tokens.

Whenever I'm sending post requests like below, it throws error: missing CSRF token

 this.$http.post('/student/signup', {
          email: this.signupData.email,
          password: this.signupData.password
        }, {
          'Content-type': 'application/json'
        })
.then(function(){})
.catch(function(){})

How do I configure CSRF tokens?

How to set headers for delete request?

Hi,
I'm trying to perform a delete request with your package, but could not set it.

this.$http.delete('/projects/delete', {
            'project': projectId
          },
            {
              headers: {
                'Authorization': 'Bearer ' + authToken,
                'Content-Type': 'application/json'
              }
            }
          )

authorization headers not working

If I set a common header it isn't working for some reason here is the code below.

this.axios.defaults.headers.common['Authorization'] = 'bearer:'+atoken;

Here is the update user method

   updateUser: function(user) {
                var _this=this;
                var atoken = this.$auth.token();

                this.axios.defaults.headers.common['Authorization'] = 'bearer:'+atoken;



                this.axios.post('api/users/updateprofile', user)
                    .then(function (response) {

                        var data=response['data'];

                        // Save Message Dialog
                        _this.$refs.updateMessage.open();

                    })
                    .catch(function (error) {
                        //console.log(error);
                    });

            }

Can't import VueAxios in typescript

I'm trying to use vue-axios in typescript project but get errors even on import:

import VueAxios from 'vue-axios'; // has no default export.
import * as VueAxios from 'vue-axios'; // resolves to a non-module entity and cannot be imported using this construct.
import VueAxios = require('vue-axios'); // Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.
import { VueAxios } from 'vue-axios'; // has no exported member 'VueAxios'.

Should consider VueAxios to be default export? Or there some other methods to import the plugin?

Versions:
vue-axios: 2.1.1
typescript: 2.8.1

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./src/main/webapp/",
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "es2015",
    "target": "es5",
    "strict": true,
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true
  }
}

Install vue-axios with no module bundler support (e.g. webpack)

The project README suggests to install this dependency with NPM

$ npm install --save axios vue-axios

but for the project I'm working on, I'm not allowed to rely on webpack. Under these conditions, can I follow the same procedure as listed in the README for installing vue-axios or is there something else I can do? Further, what do you mean when you say the following - what is the document you refer to?

Just add 3 scripts in order: vue, axios and vue-axios to your document.

vuex unknown action type while trying to post data to Django backend.

I am trying to send my vuejs front end data using Vuex and Vue-axios to the backend. I have create a vuex store and vue-axios services But I get an error saying [vuex] unknown action type: addGeneral when I try to pass the data.

This is my vuex folder structure:

-store
    -modules
        -app
            -mutations.js
            -state.js
        -general.js
        -index.js
    -actions.js
    -getters.js
    -index.js
    -mutations.js
    -state.js

This is module/general.js :

import { ApiService } from '@/services/api.service
import { FETCH_GENERAL,
   ADD_GENERAL
} from '../actions'
import { FETCH_START,
  FETCH_END,
  SET_GENERAL,
  SET_ERROR,
} from '../mutations'

const state = {
  general: [],
  errors: {},
  loading: false
};

const getters = {
  general (state) {
    return state.general;
  },
  isLoading (state) {
    return state.loading;
  }
};
const actions = {
  [FETCH_GENERAL] (context, payload) {
    context.commit(FETCH_START);
    return ApiService
      .get('general')
      .then(({data}) => {
        context.commit(FETCH_END);
        context.commit(SET_GENERAL, data.general.results);
    })
  .catch(({response}) => {
      context.commit(SET_ERROR, response.data.errors)
    })
  },
  [ADD_GENERAL] (context, payload) {
    context.commit(FETCH_START);
    return ApiService
      .postGeneral(`general`, '',payload)
      .then(({data}) => {
        context.commit(FETCH_END);
        context.commit(SET_GENERAL, data.general.results);
      })
      .catch(({response}) => {
        context.commit(SET_ERROR, response.data.errors)
      })
  }
};

const mutations = {
  [FETCH_START] (state) {
    state.loading = true
  },
  [FETCH_END] (state) {
    state.loading = false
  },
  [SET_GENERAL] (state, pgeneral) { // can pass in payload
    state.components = pgeneral;
    state.errors = {}
  },
  [SET_ERROR] (state, errors) {
    state.errors = errors
  }
};

export default {
  state,
  getters,
  actions,
  mutations
}

This is module/index.js :

const requireModule = require.context('.', true, /\.js$/)
const modules = {}

requireModule.keys().forEach(fileName => {
  if (fileName === './index.js') return

  // Replace ./ and .js
  const path = fileName.replace(/(\.\/|\.js)/g, '')
  const [moduleName, imported] = path.split('/')

  if (!modules[moduleName]) {
    modules[moduleName] = {
      namespaced: true
    }
  }

  modules[moduleName][imported] = requireModule(fileName).default
})

export default modules

This is store/actions.js :

export const FETCH_GENERAL = "fetchGeneral";
export const ADD_GENERAL = "addGeneral";
This is store/index.js :

import Vue from 'vue'
import Vuex from 'vuex'

// Store functionality
import actions from './actions'
import getters from './getters'
import modules from './modules'
import mutations from './mutations'
import state from './state'

Vue.use(Vuex)

// Create a new store
const store = new Vuex.Store({
  actions,
  getters,
  modules,
  mutations,
  state
})

export default store

This is store/mutations.js :

export const FETCH_START = "loadingOn";
export const FETCH_END = "loadingOff";
export const SET_ERROR = "setError";
// related to general
export const SET_GENERAL = 'setGeneral';
This is my vue-axios folder structure:

-services
    -api.services.js
    -config.js

This is services/api.serviecs.js :

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { API_URL } from './config'
import Cookies from 'js-cookie'

let CSRF_TOKEN = Cookies.get('csrftoken');

export const ApiService = {
  init () {
    Vue.use(VueAxios, axios)
    Vue.axios.defaults.baseURL = API_URL
  },
  get (resource, slug='') {
    return Vue.axios
        .get(`${resource}\${slug}`,)
        .catch((error) => {
          throw new Error(`ApiService ${error}`)
        })
  },
  postGeneral (resource, slug='', obj) {
    return axios
      .post(`${API_URL}\\${resource}\\${slug}`,{
        systemName: obj.systemName,
        regionOfDeployment: obj.regionOfDeployment,
        operatingMode: obj.operatingMode,
        solution: obj.solution,
        baselineMode: obj.baselineMode,
        baselineDetails: obj.baselineDetails,
        projectDuration: obj.projectDuration,
      },
        {
          headers: {
            'X-CSRFToken': CSRF_TOKEN,
            'Content-Type': 'application/json',
          }
        })
      .catch((error) => {
        throw new Error (`ApiService ${error}`)
      })
  },
}
export default ApiService

This is config.js:

export default {}
export const API_URL = 'http://127.0.0.1:8000/api';
and finally this is my vuejs component:

  ...
  <v-btn class="mt-5 mr-2 font-weight-light" color="blue" 
  @click="addGeneral" >
  ...
  methods: {


   addGeneral() {
        let obj = {
            systemName: '',
            regionOfDeployment: '',
            operatingMode: '',
            solution: '',
            baselineMode: '',
            baselineDetails: '',
            projectDuration: ''
        };
        this.postGeneral(obj)
    },
    postGeneral(obj) {
        this.$store.dispatch(ADD_GENERAL, obj)
    }

   }

Why do I get the error and what's the best way to solve it?

Works with postman but not with vue-axios

Vuejs code:

Vue.axios
      .put(
        'https://XXXXXXXXX.amazonaws.com/AAA/BBBB/saaa/records',
        JSON.stringify({ events }),
        { headers: { 'Content-Type': 'application/json', Accept: '*/*' } },
        {}
      )
      .then(x => {
        console.log(x);
      });

Postman XHR code

  "records": [
    {
      "data": "some data",
      "partition-key": "some key"
    },
    {
      "data": "some other data",
      "partition-key": "some key"
    }
  ]
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("PUT", "https://XXXXX/AAAA/BBBB/saaa/records");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("User-Agent", "PostmanRuntime/7.15.2");
xhr.setRequestHeader("Accept", "*/*");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "6904eb4c-c45c-4099-a140-08cb0319f62a,a6fb518b-2da7-41a1-8e0c-a71913c4a503");
xhr.setRequestHeader("Host", "XXXXXX.amazonaws.com");
xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
xhr.setRequestHeader("Content-Length", "230");
xhr.setRequestHeader("Connection", "keep-alive");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

receiving:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Why isn't there a Vue.$http

It would make much more sense. You also don't do: Vue.$vuex but Vue.$store. Is there any reason for this? I just tried changing

Vue.axios = axios;

to

Vue.$http = axios;

in your code and it seems to work.

Ignore baseURL on request

Hi! Is there a way to ignore the baseURL in a request? Right now i have a single get request that does not uses the baseURL that I have set and it looks like an awful solution to my problem:

this.$http.get(`${this.$http.defaults.baseURL.replace('/api', '')}${this.providerCsvUrl}`)

Thanks in advance!

Usage with VueJs 3

I'd like to use vue-axios with Vue3. When initiating app, i'll get an error.
Can you tell me what's the problem here?

import { createApp } from 'vue'
import axios from 'axios';
import VueAxios from 'vue-axios'
...

const app = createApp(App)
  .use(VueAxios, axios);

Error:

vue-axios.min.js?a7fe:1 Uncaught TypeError: Object.defineProperties called on non-object
    at Function.defineProperties (<anonymous>)
    at o (vue-axios.min.js?a7fe:1)
    at Object.use (runtime-core.esm-bundler.js?5c40:3364)
    at eval (main.ts?bc82:28)
    at Module../src/main.ts (app.js:1135)
    at __webpack_require__ (app.js:854)
    at fn (app.js:151)
    at Object.1 (app.js:1207)
    at __webpack_require__ (app.js:854)
    at checkDeferredModules (app.js:46)

How to use this library with vue-decorator-class

I like this library, I use in almost all my vue projects, but, recent, I start to use typescript with vue.js and vue-decorator-class and vue-property-decorator, and, in each file, I need to do,

import Vue from 'vue'

Before, I just needed to do:

Vue.use(VueAxios, vue)

And that was all, but, with this methodology, I don't know how to implement vue-axios for use only:

this.axios.something...

Can you help me with this?

Cannot redefine property: $http

I got this error when I use this plugin,can anyone explain why?many thanks!!
version:
Vue:2.5.16
Vue-axios:2.1.4

vue-axios.min.js?de48:formatted:18 Uncaught TypeError: Cannot redefine property: $http
at Function.defineProperties ()
at o (vue-axios.min.js?de48:formatted:18)
at Function.Vue.use (vue.esm.js?22f2:4753)
at eval (main.js?3479:14)
at Object../src/main.js (app.js:4860)
at webpack_require (app.js:708)
at fn (app.js:113)
at Object.0 (app.js:4892)
at webpack_require (app.js:708)
at app.js:806

Why?

Why use this instead of standard Axios?

There are several problems with vue-axios

In the npm.js website, the md document is wrong;

The code provided by unpkg is outdated,That is, the code in the dist folder is out of date.This will also cause the vue-axios code introduced using import to be outdated

In vue2 use, An error occurred :
image

Cannot read property 'get' of undefined

Hi!

I have an issue implementing VueAxios on Vue 3 project.

I'm installing this way:

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

createApp(App)
    .use(VueAxios, axios)
    .mount('#app')

And then, in my component:

// /components/test.js

<template>
    <button class="btn btn-primary" @click="getUser">Get user</button>
</template>

<script>

export default {
    setup() {

        function getUser() {
            this.axios.get("/api/me").then(({ data }) => {
                console.log(data);
            });
        }

        return {
            getUser,
        };
    },
};
</script>

But it throws the error Cannot read property 'get' of undefined when click on button. So maybe there is an error when installing axios globally.

Versions:

"axios": "^0.20.0",
"vue": "^3.0.0",
"vue-axios": "^3.1.1"

Abort request from vue-axios

I saw the cancellation feature for the Axios. But I am not able to cancel in vue-axios.
Is there any way that I could cancel all the API requests in the current component from beforeDestroy().

Hint: I am using Vue.axios.get() inside vue method that is triggered from created().

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.