36
loading...
This website collects cookies to deliver better user experience
Axios provides out of the box support for having a persistent configuration for all of our API calls using Axios instances. We’ll be using Axios instances as HTTP clients in our application with our configurations. If you are working on a large-scale application, it is possible that your application needs to communicate with different API endpoints. In this case, we might need to create multiple Axios instances, with their own configuration and separate them out to individual files.
$ npm install --save axios
Always consider best prictices. it is recommended to add API URLs into .env file
In .env file in the nuxt app we must add NUXT to variables. For example: NUXT_ENV_BASE_URL=https://api.myapp.test
read the documents
import axios from 'axios';
const httpClient = axios.create({
baseURL: process.env.baseUrl,
headers: {
"Content-Type": "application/json",
// anything you want to add to the headers
}
});
export default httpClient;
import httpClient from '../httpclient';
export const login = ({username, password}) => {
return httpClient({
url: '/login',
method: 'post',
headers: {
// "X-CSRF-TOKEN": getCookie('csrf_token')
},
data: {
username, password
}
});
}
export const register = ({username, password}) => {
return httpClient({
url: '/register',
method: 'post',
headers: {
// "X-CSRF-TOKEN": getCookie('csrf_token')
},
data: {
username, password
}
});
}
api/
├── httpClient.js --> HTTP Client with our configs
├── users
├──── users.api.js
├── books
├──── books.api.js
import { login, register } from '@/api/users/users.api';
/*
* store/modules/users/users.module.js
*/
import {register, login} from "~/api/users/users.api";
export const state = () => ({
user: null,
csrf_token: null
})
export const getters = {
get_user(state) {
return state.user
},
}
export const mutations = {
SET_USER_INFO(state, user) {
state.user = user
},
}
export const actions = {
loginUser({store, commit}, {username, password}) {
return new Promise(async (resolve, reject) => {
try {
const response = await login({
username, password
});
//depends on the response
commit('SET_USER_INFO', response.data)
resolve()
} catch (err) {
reject(err.response.data.message)
console.log(err)
}
})
}
}
Is it easy as response.status === 500 in every request? It's not ideal to check the status and logging these errors in every network request we make inside our actions. Instead, axios offer abilities to intercept the error responses, which is a perfect spot to find errors, log or show a cute notification to the user saying the server effed up. We can also use this to log-out the user from your application if the requests aren't authorized or if the server informs of an expired session.
import axios from 'axios';
const httpClient = axios.create({
headers: {
"Content-Type": "application/json",
}
})
// interceptor to catch errors
const errorInterceptor = error => {
// check if it's a server error
if (!error.response) {
return Promise.reject(error);
}
// all the other error responses
switch (error.response.status) {
case 401: // authentication error, logout the user
localStorage.removeItem('auth_token');
stop();
location.href = '/auth/login';
break;
default:
}
return Promise.reject(error);
}
// Interceptor for responses
const responseInterceptor = response => {
switch (response.status) {
case 200:
// yay!
break;
// any other cases
default:
// default case
}
return response;
}
httpClient.interceptors.response.use(responseInterceptor, errorInterceptor);
export default httpClient;