I installed axios using the npm install axios command this is my package.json dependencies
"dependencies": {
"axios": "^0.18.0",
"bootstrap-vue": "^2.0.0-rc.11",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
I registered the axios in my main.js file.
import Vue from 'vue'
import VueRouter from 'vue-router'
import BootstrapVue from 'bootstrap-vue'
import axios from 'axios'
import App from './App'
import routerList from './routes'
Vue.use(axios)
Vue.use(BootstrapVue)
Vue.use(VueRouter)
When I tried to use axios in one of my components I get this error:
Uncaught ReferenceError: axios is not defined
How to fix this?
Vue.use means adding plugins. However, axios is not a plugin for Vue, so you can not add it globally via use.
My recommendation is importing axios only when you need it. But if you really need to access it globally, you may like to add it to prototype.
Vue.prototype.$axios = axios
Then you can access axios in vue using this.$axios
Solution 1 (Not recommended):
In main.js, add this line instead of import axios from 'axios'
window.axios = require('axios');
And remove
Vue.use(axios)
Solution 2 (Recommended Approach):
Using window is generally considered a bad practice, so you better use axios the following way:
Create a folder named plugins inside of your src directory.
Then, create axios.js file inside that directory. We will put all our axios logic here and use axios as a Vue plugin.
Add the following:
import ax from 'axios'
// insert all your axios logic here
export const axios = ax
export default {
install (Vue, options) {
Vue.prototype.$axios = ax
}
}
In src/main.js, add the following:
import Vue from 'vue' // You can skip this line
import VueAxios from './plugins/axios'
Vue.use(VueAxios)
Now, you can use axios as this.$axios in your components. So something like this.$axios.get().
Therefore, you can import axios with the following line:
import { axios } from '#/plugins/axios'
Now, you can use axios directly in your store.
Or you can also use it as Vuex plugin:
import { axios } from '#/plugins/axios'
const axiosPlugin = store => {
store.$axios = axios
}
new Vuex.Store({
...,
plugins: [axiosPlugin]
})
Now, you can use it as this.$axios in Vuex.
Use following command to install axios
npm install axios --save
After executing above command import like mentioned below:
import axios from 'axios'
Also install vue-axios and import in main.js
import VueAxios from 'vue-axios'
Then in main.js:
Vue.use(VueAxios, axios)
Now if I am not mistaken in your methods you can use for example:
let uri = 'http://localhost:4000/tickets/add';
this.axios.post(uri, this.ticket).then((response) => {
console.log(response);
});
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios;
then inside your component you can start using axios like this:
{
methods: {
someMethod() {
this.$http.get('/users').then(() => {
// do something
})
}
}
}
Include this line:
import {AxiosInstance as axios} from "axios";
To use in Vue Components, install both Vue Axios and Axios packages
npm install --save axios vue-axios
In your main.js file, add the following:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
With the above solution, I never had an issue using axios in my Vue components with this keyword till now.
Custom Javascript File
However, I had faced issues using Axios in a custom JS file with axios not defined error.
Following worked for me in a custom JS file:
const axios = require("axios");
Usage example:
export default {
fetchProducts() {
return axios.get(`${ROOT_URL}/products`);
},
};
Try this codes:
import axios from 'axios'
Vue.use(axios)
Related
hope you are well!
I am working in a project CRUD web application that handles user management. Create user, edit user, delete user.
First I set up my project install VueJS after that installed vue-bootstrap make import in file main.js.
For mocking the Backend I have used :
NPM install -g json-server
After that, create a new file called db.json that handles users in the root of a project.
I run command json-server --watch db.json to make record available.
http://localhost:3000/users
I have installed axis for us to be able to send and receive data from our backand.
So I have run command npm install axios.
But after it how I have import axios in file main.js, but I am not confident if is the right way?? Thanks
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";
import axios from 'axios'
//Import Bootstrap an BootstrapVue CSS files (order is important)
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.config.productionTip = false
Vue.use({
install (Vue) {
Vue.prototype.$api = axios.create({
baseURL: 'http://localhost:8000/users/'
})
}
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
<script>
import axios from 'axios';
export default {
data() {
return {
posts: [],
errors: []
}
},
// Fetches posts when the component is created.
created() {
axios.get(`http://jsonplaceholder.typicode.com/posts`)
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
Do the same as shown in the script example, it will work
Fetching data from external sources is considered as a "side-effect". Thus, according to me, you should perform such side effects inside a "mounted" life cycle.
Further, to make things more better, you can create an abstraction layer for fetching data from external APIs inside "mounted" life cycle.
To make things simple on your end, you can also consider Vue-Query.
the easiest way is to create a folder known as axios in your src then add index.js in it then put this code:
// axios/index.js
import axios from "axios";
export default axios.create({
baseURL: "http://127.0.0.1:8000/api/", //your base url here
});
then import this file as axios in your app main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";
import axios from "#/axios"; //import your custom axios
I don't know how to solve this problem.
When I started project vue3.js , console show me this error.
This import in pinia store.
I tryied change first line with import to
"import Vue from 'vue';" (without curcy braces), but error don't disappear.
import { Vue } from 'vue';
import { defineStore } from 'pinia';
import moment from 'moment';
import _ from 'lodash';
import router from '#/router';
if you are using latest version of vue , vue3
this code
import { Vue } from 'vue';
is no longer global instance
I have a component called Login.js There I import Axios libray normal way and it works like this.
import axios from 'axios';
const data = await axios.post('/user/login/', {
email: e.email,
password: e.password,
});
Getting 404 is fine because I didn't set any base URL for the Axios. Please note all the requests, response headers here.
Then I try to created Axios instance inside a lib folder and import it like this
/src/lib/axios.js
import axios from "axios";
const baseUrl = process.env.REACT_APP_BE_URL;
const axiosInstance = axios.create({
baseURL: baseUrl,
});
export default axiosInstance;
I import this instance instead of normal Axios import.
import axios from 'libs/axios';
Now I see the request like this a lot of properties missing in the request and this isn't working
How do I fix this?
Any help thanks in advance.
I have installed axios via npm and try to import axios to my front end script file.
The error which i am facing is
Uncaught SyntaxError: Cannot use import statement outside a module
This is my app.js file
import axios from 'axios';
function updateRecipt(items) {
axios.post('/update-reciept',items).then(res=>{
console.log(res);
})
}
Note:I also change "type":"tag" to "type":"module" in axios package.json and import statement to const axios = require("../../node_module/axios"). but it doesnot work for me
You are using CommonJS.
To import axios you could do
const axios = require("axios");
Instead if you want to use ES Modules,
you need to go to package.jsonand add "type": "module", (you could also add "type": "commonjs", to use explicitly CommonJS)
You're using the es6 syntax instead of the commonJS. Try using this
const axios = require('axios');
If you want to use es6, you'll need something like Babel
Try putting that in another file, then do this:
const axios = require('your_file.js');
then go back to your file, and add:
import axios from 'axios';
module.exports = axios
I seem to not be able to use axios in my vue project as it's saying that 'axios' is not defined when I try using axios.get() in my file for Home.vue. Am I doing something wrong in main.js where I configure it? Or am I missing something that needs to be added? Below is my code for main.js and it shows how I'm adding axios to my project.
import Vue from 'vue';
import GSignInButton from 'vue-google-signin-button';
import ElementUI from 'element-ui';
import axios from 'axios';
import './assets/element-variables.scss';
import locale from 'element-ui/lib/locale/lang/en';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
Vue.use(ElementUI, { locale });
Vue.use(GSignInButton);
Vue.use(axios);
Vue.use(ElementUI);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
Edit: The solution for this issue for me was to install a vue plugin called vue-axios and follow the steps to configure here: https://www.npmjs.com/package/vue-axios
Try to add axios as instance global property instead of Vue.use(axios);:
Vue.prototype.$axios=axios
then you could use it in any child component like this.$axios.get()
learn more about adding-instance-properties