How to catch axios api call error 401 in reactjs? - reactjs

I am using axios to make apis calls in react. If there is no token provided or token got expired server sends the 401 status. I want to check that status on reactjs side.
But if i check err object in catch the status field is null.
Here is the code
try {
MyService.getIntet(reqBody);
} catch (err) {
handleUnAuthorizedResponse(err);
}
error returns this
Service function:
import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
headers: {
"Content-Type": "application/json"
},
};
return axios
.post(url, reqBody, options)
.then((res) => res.data)
}
How to handle 401 error ?

You need to wrap the trycatch in async function and await MyService.getIntet(reqBody) to catch the error. The status code is in err.response.status.
You could also just MyService.getIntet(reqBody).catch(handleUnAuthorizedResponse) if you don't want to wrap it in async function.

You can use .catch chaining function after .then to catch all errors.
Error object will contain a response object which will contain actual response received by API response with all meta information. But make sure to put a condition while accessing this object as errors caught from the then block will not have response key.
import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
headers: {
"Content-Type": "application/json"
},
};
return axios
.post(url, reqBody, options)
.then((res) => res.data)
.catch(error => console.log(error.response.status))
}

Related

NextJS API Endpoint Error - 'API resolved without sending a response for /api/foo, this may result in stalled requests.'

This is the code I am using
// function calling the api endpoint within a button onClick event handler
async () => {
const response = await fetch('/api/foo', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
const responseData = await response.json()
}
// /api/foo.js
import { ref, uploadString } from 'firebase/storage'
import { storage } from './firebase'
export default async function handler(req, res) {
const data = req.body
const storageRef = ref(storage, data.ID)
const uploadTask = uploadString(storageRef,
JSON.stringify(data.object)
).then(snapshot => {
res.status(200).json(
{ message: 'Saved!', severity: 'success' })
res.end()
}
)
}
When a request is sent to the above API endpoint, the console in vscode shows that a request was sent with this error: API resolved without sending a response for /api/foo, this may result in stalled requests.
What does this mean and how is it fixed?
Thanks in advance!
Edit - added async to handler function, but error still showing

How to send a POST/GET request from a middleware file in Next.js?

I am trying to send a GET request directly in the middleware file but unfortunately I am getting a weird error message. This is my middleware file:
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
await fetch(new URL("http://api.tvmaze.com/search/shows?q=postman").href, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response;
}
Unfortunately, when I try that, the error message is:
[TypeError: Cannot delete property 'Symbol(set-cookie)' of
#]
Do you have any idea why I'm getting this error message?

i'm getting auth token response for linkedin in postman but don't know how to convert it into axios

i want to get post request response from axios if I have token code I'm able to do that in postman but not able to complete it in axios
here is the postman response and all the require data I have to pass in postman
what I did to get the response in react
React.useEffect(() => {
if (code) {
let configData = {
client_id: 'hjhdjd',
client_secret: 'e637833ndd',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000/linkedin/callback',
code: code,
};
console.log(configData);
axios(
configData
)
.then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});
}
}, [code]);
but after doing this I'm getting error given below
TypeError: Cannot read properties of undefined (reading 'protocol')
You must call methods of axios, in this case you should use post:
axios.post(url,configData).then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});

Handling errors within custom SWR hook

I've written a custom hook that uses SWR to retrieve data from my API whilst setting the 'Authentication' header for the request.
The hook is working fine for all successful requests but I want to be able to handle failed requests (400 status codes).
I'm able to access the status code with the result from const res = await fetch(url but how do I return the error in the error parameter to the caller of the hook?
import useSWR from 'swr';
export default function useAPI(path) {
const auth = useAuth();
const { data, error, isValidating, mutate } = useSWR(
!path ? null : `${process.env.NEXT_PUBLIC_API_URL}${path}`,
async (url) => {
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${auth.user.token}`,
accept: 'application/json',
},
});
return res.json();
}
);
return { data, error, isValidating, mutate };
}
From SWR Error Handling documentation:
If an error is thrown inside fetcher, it will be returned as error by the hook.
In your case, you can simply handle to 400 status code response in the fetcher and throw an error after the handling is done.
const { data, error, isValidating, mutate } = useSWR(
!path ? null : `${process.env.NEXT_PUBLIC_API_URL}${path}`,
async (url) => {
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${auth.user.token}`,
accept: 'application/json'
}
});
if (res.statusCode === 400) {
// Add your custom handling here
throw new Error('A 400 error occurred while fetching the data.'); // Throw the error
}
return res.json();
}
);

How to fix the unauthorized axios/react response

Unauthorized axios/react response
Hi there friends, I'm trying to connect to an api through Axios and React but an error message appears saying that I don't have access here's my action:
import {SHOW_PROMOTIONS} from './action-types';
import axios from 'axios';
export const showPromo = () => async dispatch =>{
const url= 'https://payment-promotions-dev.travelit.com.ar/api/promotions/packages/';
let config = {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
};
axios.get('http://<host>:<port>/<path>', url,config)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
const respuesta = await axios.get(url,config);
dispatch({
type: SHOW_PROMOTIONS,
payload: respuesta.data
})
}
When I execute the component, this error appears: (See following image https://imgur.com/LuKnBv9)
The token is at it's respective header, I don't seem to recognize wat I'm doing wrong.
I even tried to do the request with Postman and it throughs 200: (See image2 https://imgur.com/7UFksPR)
Thanks for the help guys!
You currently aren't actually specifying headers for the request. You would need to add headers property to the config object and put the desired headers into that property. Also, as the comments have you stated, you would also need to specify the type for the Authorization request headers, such as Bearer:
const config = {
headers: {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
}
};
Hopefully that helps!

Resources