Where do I put my config in this axios request? - javascript

If I put my config as the second argument, my cancellation token (third arg) gets ignored. However I need the Authorization header because this get request will be (but isn't yet!) Behind authentication middleware on my node API. So my question is: Where do I put my config?
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
};
const getBoards = async (cancelToken) => {
try {
if (localStorage.getItem("token") == null) {
throw new Error();
}
const response = await Axios.get("/boards", {
cancelToken: cancelToken.token,
});
setBoards(response.data);
} catch (e) {}
};
useEffect(() => {
const request = Axios.CancelToken.source();
getBoards(request);
return () => {
request.cancel();
};
}, []);

pass them in the same object.
const response = await Axios.get("/boards", {
headers: {},
cancelToken: cancelToken.token,
});

Related

Passing query params or body with NextJS + Auth0?

So, my knowledge of next and JS in general is extremely minimal as is my Auth0 knowledge. I was wondering if anyone could suggest how to pass query parameters or a request body to the first block of code below?
I know I can add a body to the fetch function, but when I try to do that in the /pages/profile block below, it seems to break the request.
Even better would be to make this some kind of generic function, where I can pass in a the route, method, and body since all of the routes will be protected anyway.
Any help would be greatly appreciated.
/pages/api/my/user
import { getAccessToken, withApiAuthRequired } from '#auth0/nextjs-auth0';
export default withApiAuthRequired(async function shows(req, res) {
try {
const { accessToken } = await getAccessToken(req, res, {
scopes: ['profile']
});
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/my/user`, {
headers: {
Authorization: `Bearer ${accessToken}`
},
});
const shows = await response.json();
res.status(200).json(shows);
} catch (error) {
res.status(error.status || 500).json({ error: error.message });
}
});
And here's the snippet that fetches the above:
/pages/profile
const [state, setState] = useState({ isLoading: false, response: undefined, error: undefined });
useEffect(() => {
callApi();
}, []);
const callApi = async () => {
setState(previous => ({ ...previous, isLoading: true }))
try {
const response = await fetch(`/api/my/user`);
const data = await response.json();
setState(previous => ({ ...previous, response: data, error: undefined }))
} catch (error) {
setState(previous => ({ ...previous, response: undefined, error }))
} finally {
setState(previous => ({ ...previous, isLoading: false }))
}
};
const { isLoading, response, error } = state;
Cannot see where your actual problem is - here's a snippet that usually works for me with fetch:
provide headers and body as parameters of an options variable, add the url and you are good to go.
const res = await fetch(url, options)
const protocol = 'https'
const hostname = 'YOURHOSTNAME'
const queryParams = `foo=bar`
const body = []
const url = `${protocol}://${hostname}/api/${endpoint}?${queryParams}`;
const options = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': `${hostname}`, // set as needed
},
body: body,
method: 'POST',
};
const res = fetch(url, options);
Hope this helps

How to set two interceptors in axios

I have two functions that using axios post information to different APIs I created with node and express. Both of them have an interceptor as I get a response from by backend with messages, errors, and other information. Yet when I post the to the second url ("/users/login") the first interceptor still fires off (in the addUser instead of the findUser function) even though it is not in the same function. How do I fix this?
async function addUser(user) {
const config = {
headers: {
"Content-Type": "application/json",
},
};
try {
const interceptorResponse = axios.interceptors.response.use(
(response) => {
if (typeof response.data === "object") {
let success = response.data.registerSuccess;
let errors = response.data.errors;
let data = response.data.data;
let message = response.data.message;
setData(() => {
return { ...data, errors, registerSuccess: success, message };
});
}
return response;
}
);
await axios.post("/users/register", user, config);
axios.interceptors.request.eject(interceptorResponse);
} catch (err) {}
}
async function findUser(user) {
const config = {
headers: {
"Content-Type": "application/json",
},
};
try {
axios.interceptors.response.use((response) => {
console.log(response);
if (typeof response.data === "object") {
let loginSuccess = response.data.data.loginSuccess;
let message = response.data.message;
console.log(response.data);
setData(() => {
return { ...data, loginSuccess, message };
});
}
return response;
});
await axios.post("/users/login", user, config);
} catch (error) {}
}

How prevent fetch request before auth token is received in React Js?

I have a separate fetch request function that logins user and saves auth token to localStorage, then my data request fetch should be send with that saved token bearer, but data fetch doesn't wait for token and receives Unauthorized access code.
My data request fetch looks like this :
// to check for fetch err
function findErr(response) {
try {
if (response.status >= 200 && response.status <= 299) {
return response.json();
} else if (response.status === 401) {
throw Error(response.statusText);
} else if (!response.ok) {
throw Error(response.statusText);
} else {
if (response.ok) {
return response.data;
}
}
} catch (error) {
console.log("caught error: ", error);
}
}
const token = JSON.parse(localStorage.getItem("token"));
// actual fetch request
export async function getData() {
const url = `${URL}/data`;
var obj = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + `${token}`,
},
};
const data = await fetch(url, obj)
.then((response) => findErr(response))
.then((result) => {
return result.data;
});
return data;
}
My fetch requests are in a different js file, I'm importing them in my components like this:
import React, { useState, useEffect } from "react";
function getInfo() {
const [info, setInfo] = useState()
const importGetDataFunc = async () => {
const data = await getData();
setInfo(data);
};
useEffect(() => {
importGetDataFunc();
}, []);
return (
<div>
</div>
)
}
export default getInfo
Now when I go to the getInfo component after login at first fetch request returns 401, but after I refresh the page fetch request goes with token bearer and data gets returned. My problem is that I don't know how to make getData() fetch request to wait until it gets token from localStorage or retry fetch request on 401 code. I tried to implement if statement like this
useEffect(() => {
if(token){
importGetDataFunc();
}
}, []);
where useEffect would check if token is in localStorage and only then fire fetch request, but it didn't work. Any help on how I can handle this would be greatly appreciated.
You are close. You need to add token as a dependency to your useEffect. Also, you need to move your token fetching logic into your component.
Something like this should work:
import React, { useState, useEffect } from "react";
function getInfo() {
const [info, setInfo] = useState()
const token = JSON.parse(localStorage.getItem("token"));
const importGetDataFunc = async () => {
const data = await getData();
setInfo(data);
};
useEffect(() => {
if(token) {
importGetDataFunc(token);
}
}, [token]);
return (
<div>
</div>
)
}
export default getInfo
You can also modify your importGetDataFunc to receive the token as a parameter.
const importGetDataFunc = async (token) => {
const data = await getData(token);
setInfo(data);
};
export async function getData(token) {
const url = `${URL}/data`;
var obj = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + `${token}`,
},
};
const data = await fetch(url, obj)
.then((response) => findErr(response))
.then((result) => {
return result.data;
});
return data;
}
What actually helped me is to make a function to check for a token inside get fetch request, like this:
export const findToken = () => {
const token =localStorage.getItem("token")
return token;
};
export async function getData(token) {
const url = `${URL}/data`;
var obj = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + `${findToken()}`,
},
};
const data = await fetch(url, obj)
.then((response) => findErr(response))
.then((result) => {
return result.data;
});
return data;
}

ReactJS Hook error handeling doesn't catch errors

I am trying to catch a 404 error I receive for some of my API calls.
I am using the matrix API and need to get room names from their id's, which is working. Some of them don't have names which returns a 404 error I am trying to catch. Unfortunately this dosn't work and I don't understand where I'm going wrong. The code itself exectues, but it still throws 404's in the console.
const JoinedRooms = () => {
const [answer, setAnswer] = useState([]);
const [isError, setIsError] = useState(false);
const getAnswer = async () => {
const res = await fetch(`https://example.com/_matrix/client/r0/joined_rooms`, {
headers: {
"Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
}
});
const answer = await res.json();
const getNames = await Promise.all(answer.joined_rooms.map(async (roomId) => {
setIsError(false);
const res = await fetch(`https://example.com/_matrix/client/r0/rooms/${roomId}/state/m.room.name`, {
headers: {
"Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
}
});
try {
const roomName = await res.json();
return roomName.name;
} catch (error) {
setIsError(true);
}
}));
setAnswer(getNames);
}
useEffect(() => {
getAnswer();
}, []);
return answer;
}
export default JoinedRooms;
A 404 status code will not throw an error, so your try...catch block won't catch it. Try getting the 404 directly from the res object returned.
const res = await fetch(`https://example.com/_matrix/client/r0/rooms/${roomId}/state/m.room.name`, {
headers: {
"Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
}
});
if (res.status === 404) {
// handle error
}

Way to handle refresh token

I am working on login feature and have problem when refresh token.
When token expire making request to refresh token, remove the old token, and save the new token to AsyncStorage.
After login successfully have to function A and B. The function A is using the new token to make its request. the function B say that it need to refresh the token so make request to refresh token ( the request make successfully, token being refresh) but The token that request A is using now invalid - I think it happens due to asynchronous
This is my code that use to refresh token:
axiosInstance.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
if (error.response.status === CODE_TOKEN_EXPIRED) {
try {
const token = await authenticationService.getRefreshToken();
const response = await authenticationService.refreshToken(token);
await authenticationService.removeToken();
await authenticationService.storeToken(response.data.params.access_token);
await authenticationService.storeRefreshToken(response.data.params.refresh_token);
error.config.headers.Authorization = 'Bearer ' + response.data.params.access_token;
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.params.access_token;
return axiosInstance(error.config);
} catch (err) {
console.log(2, err);
await authenticationService.removeToken();
navigationService.navigate('LoginForm');
}
}
return Promise.reject(error);
}
);
Anyone know how to handle which asynchronous call for refresh token?
First would be for you to check if you are changing token to the correct axios instance. It is necessary to change Authorization header on error.response config as you did, but also for main axios instance (if you have one) like so: axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
If it is multiple parallel requests going on that could possibly need to be postponed after token is refreshed issue and answer gets complex, but check this gist with full refresh logic with axios.
I have implemented the same scenario in fetch API. you can also do this same in axios API. Try this to avoid interceptor concept.
Api.ts
export const api = ({ method, url, body, isProtected = true }) => {
return new Promise((resolve, reject) => {
const payload = {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
};
if (body !== null) {
(payload as any).body = JSON.stringify(body);
}
/**
* "isProtected" is used for API call without authToken
*/
if (isProtected) {
AsyncStorage.getItem(ACCESS_TOKEN).then(accessKey => {
(payload.headers as any).Authorization = `Bearer ${accessKey}`;
fetch(url, payload)
.then((response: any) => {
/*
* 419 status denotes the timeout of authToken
*/
if (response.status == 419) {
// refresh token
AsyncStorage.getItem(REFRESH_TOKEN).then(refreshKey => {
const payloadRef = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + refreshKey
}
};
/*
* This call refresh the authToken using refreshing call to renew the authToken
*/
fetch(URL.baseUrl + "/refresh", payloadRef)
.then((response: any) => response.json())
.then(response => {
/*
* if refresh token expired. redirect to login page
*/
if (response.status !== codes.SUCCESS) {
if (!User.sessionOver) {
User.sessionOver = true;
Alert.alert(
'Alert',
'Session Timeout',
[
{
text: 'Get back to Login',
onPress: () => {
// get to Login page
}
}
],
{ cancelable: false }
);
}
} else if (response.status == codes.SUCCESS) {
/*
* If refresh token got refreshed and set it as authToken and retry the api call.
*/
AsyncStorage.setItem(ACCESS_TOKEN, response.payload.access_key).then(() => {
(payload.headers as any).Authorization = 'Bearer ' + response.payload.access_key;
fetch(url, payload)
.then(response => response.json())
.then(response => {
if (response.status == codes.SUCCESS) {
resolve(response);
}
})
.catch(error => {
reject(error);
});
});
}
});
});
} else {
resolve(response.json());
}
})
.catch(error => {
reject(error);
});
});
} else {
fetch(url, payload)
.then((response: any) => {
response = response.json();
resolve(response);
})
.catch(error => {
reject(error);
});
}
});
};
MovieService.ts
import { api } from '../services/api';
import { URL } from '../config/UrlConfig';
const getMovies = () => {
const method = 'GET';
const url = URL.baseUrl + '/v1/top/movies';
const body = null;
const isProtected = true;
return api({ method, url, body, isProtected });
};
export { getMovies };
Maybe it will helps - https://gist.github.com/ModPhoenix/f1070f1696faeae52edf6ee616d0c1eb
import axios from "axios";
import { settings } from "../settings";
import { authAPI } from ".";
const request = axios.create({
baseURL: settings.apiV1,
});
request.interceptors.request.use(
(config) => {
// Get token and add it to header "Authorization"
const token = authAPI.getAccessToken();
if (token) {
config.headers.Authorization = token;
}
return config;
},
(error) => Promise.reject(error)
);
let loop = 0;
let isRefreshing = false;
let subscribers = [];
function subscribeTokenRefresh(cb) {
subscribers.push(cb);
}
function onRrefreshed(token) {
subscribers.map((cb) => cb(token));
}
request.interceptors.response.use(undefined, (err) => {
const {
config,
response: { status },
} = err;
const originalRequest = config;
if (status === 401 && loop < 1) {
loop++;
if (!isRefreshing) {
isRefreshing = true;
authAPI.refreshToken().then((respaonse) => {
const { data } = respaonse;
isRefreshing = false;
onRrefreshed(data.access_token);
authAPI.setAccessToken(data.access_token);
authAPI.setRefreshToken(data.refresh_token);
subscribers = [];
});
}
return new Promise((resolve) => {
subscribeTokenRefresh((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
resolve(axios(originalRequest));
});
});
}
return Promise.reject(err);
});
export default request;

Categories