I'm trying to send the Authorization header inside of all requests, when user is logged in my application.
but, whatever i do, it does not work.
Here is my axios instance and interceptor code.
import axios from 'axios'
import storage from '#/services/storageService'
const user = storage.getObject('currentUser')
export const http = axios.create({
baseURL: 'http://localhost/api',
})
http.interceptors.request.use((config) => {
if(user){
console.log(user)
config.headers.Authorization = user.token
}
return config
}, (err) => {
console.log(err)
return Promise.reject(err)
})
in my modules i'm importing the http instance like this
import { http } from '#/http'
export const getItems = () => {
return http.get('items').then( response => response.data)
}
So, clarifying, this code above works, but the header is not present on my request.
To get the interceptor working i need to force a page reload.
Anyone know how can i avoid this?
I solved my problem following #jacky's tip. Now my code runs as following.
import axios from 'axios'
import storage from '#/services/storageService'
export const http = axios.create({
baseURL: 'http://localhost/api',
})
http.interceptors.request.use((config) => {
let user = storage.getObject('currentUser')
if(user){
console.log(user)
config.headers.Authorization = user.token
}
return config
}, (err) => {
console.log(err)
return Promise.reject(err)
})
Related
I am currently programming a small login api and have implemented it with my react native project using axios request. But i have a problem now my server send an error status code with a message but in the react antive app it only comes to an exception with the status code and not with the message. How can I best solve this do I have to take the status code out of the server and just send text back or is there another solution?
My React Native api.js:
import axios from "axios";
import AsyncStorage from "#react-native-community/async-storage";
const instance = axios.create({
baseURL: "http://example.com",
});
instance.interceptors.request.use(
async (config) => {
const token = await AsyncStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
My React Native api trigger:
const Signup = async ({email, password}) => {
try{
const response = await myApi.post("/api/signup", { email, password });
if (response.data.token){
navigation.navigate('setup');
}else{
setError(response.data);
}
}catch (err){
console.log(err);
setError('Internet Error');
}
}
and my server response
return res.status(400).send({
message: "Email or password incorrect!",
});
I try to implement axios interceptor, for my request.
So when the error response is forbidden (401), I want to clear token and navigate to login screen.
But when I want to call useNavigation from react navigation v5 inside my axios file, it always shows error like this.
React Hook "useNavigation" is called in function "refreshAccessToken" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter.
This is my axios file code,
import axios from 'axios'
import AsyncStorage from '#react-native-community/async-storage'
import {useNavigation} from '#react-navigation/native'
import {generateRandomString, getDeviceInfo} from '../helper/helper'
const base = axios.create({
baseURL: '------',
timeout: 500000,
headers: {
'Content-Type': 'application/json'
}
})
async function refreshAccessToken() {
const navigation = useNavigation()
try {
const refreshToken = await AsyncStorage.getItem('refreshToken')
const response = await base.get('------', {
refreshToken
})
await AsyncStorage.setItem('accessToken', response.data.accessToken)
console.log('Response from refresh access token ', response)
return Promise.resolve(response.data)
} catch (error) {
console.log('Error from refresh access token', error.response)
if (error.response.data.errors.flag === 'INVALID_REFRESH_TOKEN') {
await AsyncStorage.removeItem('refreshToken')
await AsyncStorage.removeItem('accessToken')
}
return Promise.reject(error)
}
}
base.interceptors.request.use(
async function (config) {
const accessToken = await AsyncStorage.getItem('accessToken')
config.headers.authorization = accessToken
const deviceInfo = await getDeviceInfo()
const latitude = await AsyncStorage.getItem('latitude')
const longitude = await AsyncStorage.getItem('longitude')
config.headers['accept-language'] = 'id-ID'
config.headers['version'] = '1.0.0'
config.headers['date'] = new Date().toUTCString()
config.headers['x-coordinate'] = `${latitude};${longitude}`
config.headers['x-trace-id'] = generateRandomString()
config.headers['x-device'] = `${deviceInfo.deviceType}/${deviceInfo.deviceName}/${deviceInfo.deviceVersion}/${deviceInfo.deviceUid}`
return config
},
function (error) {
return Promise.reject(error)
}
)
base.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config
if (error.response.status === 403 && !originalRequest._retry) {
originalRequest._retry = true
const accessToken = await refreshAccessToken()
originalRequest.headers.Authorization = accessToken
return axios(originalRequest)
}
return Promise.reject(error)
}
)
export default base
You can't, hooks are only meant to be called inside components. There is a guide on how to navigate without the navigation prop you could use for this situation though.
You could also send an event (via a custom event emitter) and set up a listener anywhere else in your app where the navigation prop is available.
i have a interceptor with axios but i don't know where to ubicate it. i attach javascript
import axios from 'axios';
import {getStoreData, checkStoreData} from './../utils/safestorage';
axios.interceptors.request.use(
async config => {
console.log('interceptor working');
const checkUser = await checkStoreData('user');
if (checkUser) {
const data = await getStoreData('user');
datajson = JSON.parse(data);
config.headers.Authorization = `Bearer ${datajson.access_token}`;
return config;
}
},
error => {
return Promise.reject(error);
},
);
I solved it importing the file in my app.js, an then my interceptors initialized.
I have configured axios plugin onRequest helper to set Authorization header on API requests like below
1. export default function({ $axios, redirect, app, store }) {
2. $axios.onRequest(config => {
3. var requestURL = config.url;
4. console.log("Making request to " + requestURL);
5. const token = store.state.user.account.token;
6. if (token) {
7. config.headers.common["Authorization"] = `Bearer ${token}`;
8. console.log("Added authorization header");
9. }
10. });
This onRequest helper get invoked for actions in store. But for asyncData in page component, call reaches till line 2 above but never enters the onRequest function.
import axios from "axios";
asyncData({ params }) {
console.log("params: " + params);
return axios
.get(`http://localhost:8080/user/id/${params.id}`)
.then(res => {
return { userData: res.data };
})
.catch(e => {
error({ statusCode: 404, message: "User not found" });
});
}
As I understand all Axios requests should pass through onRequest helper function. Am I missing something here? How to fix this?
When you import axios from 'axios' you're not using the configuration for the axios instance that you specified initially. Instead, you're using an entirely new axios instance.
The correct way would be to leverage the $axios instance from the Nuxt context.
asyncData(context) {
await context.$axios...
}
You can also use the $axios instance directly. An example is:
asyncData({$axios}) {
await $axios...
}
I did create a service for authentication in vuejs
import axios from "axios";
var authenticateService = {
login: function(Username, Password) {
var form = new FormData();
form.append("username", Username);
form.append("password", Password);
return axios.post(LOGIN_API, form);
}
}
export default authenticateService;
I want to use this service in my main.js, where I have got an axios interceptor. I have interceptor which relogins if received any 401 response from server
import authenticateService from "./service/AuthenticationService";
import axios from "axios";
axios.interceptors.response.use(undefined, err => {
let res = err.response;
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
return new Promise((resolve, reject) => {
authenticateService//Error here. authenticateService undefined
.login('user1username', 'user1password')
.then(result => {
localStorage.setItem("expire_time", response.data.expires_in);
localStorage.setItem("access_token", response.data.access_token);
err.config.__isRetryRequest = true;
err.config.headers.Authorization =
"Bearer " + response.data.access_token;
resolve(err);
})
.catch(e => {
localStorage.removeItem("expire_time");
localStorage.removeItem("access_token");
reject(e);
});
});
}
});
This interceptor throws error saying "authenticateService is not defined". Though I have imported the authenticateService, I get it undefined. Not sure what I did wrong here.
Edit return axios object from login function