Last active
March 4, 2020 10:53
-
-
Save xbits/034eea25b8d23f22a919789fd44fbf4f to your computer and use it in GitHub Desktop.
Example axios client for devise_token_auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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