Skip to content

Instantly share code, notes, and snippets.

@xbits
Last active March 4, 2020 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xbits/034eea25b8d23f22a919789fd44fbf4f to your computer and use it in GitHub Desktop.
Save xbits/034eea25b8d23f22a919789fd44fbf4f to your computer and use it in GitHub Desktop.
Example axios client for devise_token_auth
/*
This is an example of how to set up an axios instance to work with devise_token_auth gem.
*/
import axios from 'axios';
// Add the token headers to every request
const addTokenHeaders = (request) => {
let tokenAuth = localStorage.tokenAuth;
if(tokenAuth) {
request.headers = {...request.headers, ...JSON.parse(tokenAuth)}
}
return request;
}
// Extract the new token headers after every request
const extractTokenHeaders = (response) => {
let {headers} = response
if(headers && headers['access-token']){
let tokenAuth = {
"access-token": headers["access-token"],
"token-type": headers['token-type'],
"client": headers['client'],
"expiry": headers["expiry"],
"uid": headers['uid']
}
localStorage.setItem('tokenAuth', JSON.stringify(tokenAuth));
}
return response;
}
// if your API is under APP_DOMAIN/api/vi
const axiosClient = axios.create({baseURL: '/api/v1/'});
axiosClient.interceptors.request.use(addTokenHeaders)
axiosClient.interceptors.response.use(extractTokenHeaders)
export default axiosClient;
/*
Example of how you could use the client in other parts of you app.
*/
import axiosClient from "../../lib/axiosClient";
// Sign in a new user, the token will be captured on the axiosClient and available to future requests
// Notice: This assumes you mounted the devise_token_auth engine under your api and kept the default routes
axiosClient.post('auth/sign_in', {nickname: 'some_valid_name', password: 'some_valid_pass' } )
.then(response => {
console.log("Login response:", response)
console.log("User data:", response.data)
})
.catch(error => console.log("Sign in Error", error))
// Validate the token and assert the user is logged in
axiosClient.get('auth/validate_token')
.then(response=>{
console.log("Token validation response", response)
console.log("User data:", response.data.data)
})
.catch(error => console.log('Token validation error', error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment