Processing 302 Redirects with Axios
Implementation Workflow
The workflow for handling 302 redirects involves these key stages:
1. Initial Request → 302 Response → Extract Location → Follow Redirect → Final Response
Implementation Steps
- Configure Axios Instance
Create an Axios instance with redirect handling disabled to manually process 302 responses:
const axiosInstance = axios.create({
maxRedirects: 0,
validateStatus: status => status < 400 || status === 302
});
- Initial Request and Redirect Detection
Send the enitial request and check for 302 status:
axiosInstance.get('https://example.com/api')
.then(response => {
if (response.status === 302) {
const redirectUrl = response.headers.location;
return handleRedirect(redirectUrl);
}
return processResponse(response);
})
.catch(handleError);
- Redirect Handler Functon
Implmeent the redirect processing logic:
function handleRedirect(url) {
return axios.get(url)
.then(processResponse)
.catch(handleError);
}
function processResponse(response) {
// Handle successful response data
return response.data;
}
function handleError(error) {
console.error('Request failed:', error);
throw error;
}
- Complete Implementation
Combining all components into a unified solution:
async function fetchWithRedirects(url) {
try {
const response = await axiosInstance.get(url);
if (response.status === 302) {
return await axios.get(response.headers.location);
}
return response.data;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}