How to set axios as a default prototype for Nuxt.js and append token to the default axios authorization header? - axios

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

Related

NuxtJs axios module global config

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.

Nuxt vuex - moving store from Vue

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)
}
}
}

Why is axios not using the settings in nuxt.config.js?

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(...)

share a method of use axios globally standard for nuxtjs?

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
})

Can't set Authentication header for Apollo client

I'm working on a Laravel application that uses React and Redux on the client side, with the React preset and Mix. I've decided to try out GraphQL for the API rather than the usual REST API approach and it's working OK so far. However, I've now got stuck.
I'm using Apollo as my HTTP client since it's built for working with GraphQL. In the past I've used JWT Auth for securing APIs, so naturally I've gone for that approach here too, since implementation is just a case of adding an appropriate header. I've followed the instruction on setting headers with Apollo, but the headers aren't getting set. Here's the JS file in question:
import LinkList from './components/LinkList';
import React from 'react';
import ReactDOM from 'react-dom';
import {Container} from './container';
import {createStore} from 'redux';
import reducer from './reducer';
import {Provider} from 'react-redux';
import {fromJS} from 'immutable';
import ApolloClient from 'apollo-boost';
import gql from 'graphql-tag';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = createHttpLink({
uri: window.initialData.graphql_route
});
const authLink = setContext((_, { headers }) => {
const token = window.initialData.jwt;
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
client.query({
query: gql`{
links {
id
title
link
}}`
}).then(result => console.log(result));
const store = createStore(
reducer,
fromJS(window.initialData),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
if (document.getElementById('list')) {
ReactDOM.render(
<Provider store={store}>
<Container />
</Provider>,
document.getElementById('list')
);
}
I populate window.initialData in the view, and that contains the necessary data, including the JWT token as window.initialData.jwt. Setting a breakpoint inside the definition of authLink does nothing, implying that it never gets called.
Any idea what's gone wrong? I've followed the examples in the documentation pretty closely, so all I can think of is that they might be put of date.
Info: Don't save your token in the localStorage Is it safe to store a JWT in localStorage with ReactJS?
You are using the ApolloClient from 'apollo-boost', but your token configuration is for another ApolloClient, the { ApolloClient } from 'apollo-client'.
If you want to save the token using the ApolloClient from apollo-boost:
const client = new ApolloClient({
uri: ...,
request: async operation => {
const token = localStorage.getItem('token');
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : ''
}
});
}
});
Apollo Boost migration