i want use it for all components and pages and my config present :
~/plugins/axios
import axios from 'axios'
export default axios.create({
baseURL: 'http://127.0.0.1:3001/'
})
but with this way , i must import axios from '~/plugins/axios' in components and pages
i want use something choise for like this :
this.$axios.post('url',data).then(res=>{
// do something in here
}).catch({
// do something in here
})
and no need import more axios
I recommend you to use the official "Axios Module" for Nuxt.js: https://github.com/nuxt-community/axios-module
npm install #nuxtjs/axios
First, you can set your baseURL in the nuxt.config.js or in an env variable (see https://axios.nuxtjs.org/options):
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://127.0.0.1:3001/' // or, Environment variable API_URL_BROWSER can be used to override browserBaseURL.
}
Then in <page>.vue, no more import, axios is injected in the app var (see https://axios.nuxtjs.org/usage):
<script>
export default {
asyncData ({ app }) {
app.$axios.$get(`/api/users`).then(
// do something in here
);
//...
}
}
</script>
Finally, you can handle errors globally with a custom plugin (see https://axios.nuxtjs.org/extend)
$axios.onError(error => {
// do something in here
})
Related
I need to set global configuration for #nuxt/axios.
For example I need default Content-Type, Accept, Authorization header etc. and other configurations for all of my API calls. Is there any way to add these settings globally in nuxt to avoid repetition of code.
As stated here: https://axios.nuxtjs.org/extend
You can create a plugin and dump your axios configuration there like this
nuxt.config.js
export default {
plugins: [
'~/plugins/axios'
]
}
/plugins/axios.js
export default ({ $axios, $config: { baseUrlIam, secretToken } }) => {
$axios.defaults.baseURL = baseUrlIam
$axios.defaults.headers.Authorization = secretToken
}
Also, setHeader may be useful.
In Vue.js simply we can include axios as our deafault prototype for Vue.js and append local storage token to a default axios authorization header in the Vue main.js file .
As follows:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = axios;
const token = localStorage.getItem("token");
if(token){
Vue.prototype.$http.defaults.headers.common['Authorization'] = token;
}
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
My question is how to set axios as a default prototype for Nuxt.js and append local storage token to a default axios authorization header inside the Nuxt.config.js File
Not sure that the prototype is the way to go usually.
I do recommend this one for Nuxt
Install nuxt/axios with
yarn add #nuxtjs/axios
Then, go to your Nuxt configuration
nuxt.config.js
plugins: ['#/plugins/nuxt-axios.js'],
modules: ['#nuxtjs/axios'],
And set the configuration to your axios as you wish
/plugins/nuxt-axios.js
export default ({ $axios }, $config: { authorizationToken }) => {
$axios.defaults.headers.Authorization = authorizationToken
}
Or directly in the configuration file
nuxt.config.js
axios: {
headers: {
Authorization: process.env.TOKEN,
},
},
If you wish more info with the env variables, you can check this one: https://stackoverflow.com/a/67705541/8816585
I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
I have a javascript variable (var testButton) in my Nuxt plugins folder. I then added the file to my nuxt.config.js plugins. In my component, I have a Buefy button, and I'm trying to call the script:
<b-button #click="testButton">Click Me</b-button>
...
<script>
export default {
mounted () {
this.$testButton()
}
}
</script>
I import the script in my script section and have tried computed and mounted lifecycles. Not sure what I'm doing wrong. Thank you
Check the following things, you must be missing one or more:
1. Your plugin should export a method. That method should receive an 'inject' function and use it to register your 'testButton' function.
So, in your ~/plugins/testButton.js
export default (context, inject) => {
inject('testButton', () => {
console.log('testButton works!')
})
}
2. You shuold register your plugin correctly in the nuxt.conf.js file
Do it like so:
plugins: [
{ src: '~/plugins/testButton.js' },
],
3. Call it as '$testButton()' (note that Nuxt will have added a dollar sign to your method's name).
Your '$testButton' method will now be available from anywhere in your nuxt app. You don't have to import it o create any computed property.
<b-button #click="$testButton">Click Me</b-button>
<script>
export default {
}
</script>
The axios settings for baseURL and browserBaseURL in nuxt.config.js are not being used by axios and the requests are going to localhost instead.
Here's an extract of nuxt.config.js:
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://192.168.8.137:8081',
browserBaseURL: 'http://192.168.8.137:8081'
},
And here's the code in the vue file:
<template>
<v-treeview
v-model="tree"
:open="open"
:items="items"
activatable
item-key="id"
:load-children="listDir"
:active.sync="active"
return-object
>
....
</template>
<script>
import axios from 'axios'
export default {
....
methods: {
async listDir(item) {
// let url = 'http://192.168.8.137:8081/filemanager/ls' // Works fine if hardcoded here
let url = '/filemanager/ls'
await axios.get(url)
.then(....
I think the problem is that I'm using axios.get(url) and not $this.axios.get(url), however my method is being called from a vuetify treeview component and $this is not available.
How do I get hold of $this.axios?
The code works fine if I hardcode the URL into the axios call.
using
import axios from 'axios'
you are importing "clean" axios module.
You need to use axios instance created by nuxt itself.
In component (or in Vue actions) use just (without importing axios)
this.$axios.get(...)
or (convenient $get method returns response data instead response object)
this.$axios.$get(...)