Home > Software engineering >  React provide default authentication for all request
React provide default authentication for all request

Time:02-04

I'm using React with axios mainly. There I have an interceptor for API calls to refresh my JWT token when it expires.

<img src="/media/cache/img.jpg" alt={row.id} width={45} height={45}>

These are also loaded from the server and authentication is needed. But when the token expires and no API query is needed, these images won't load because the token is invalid and authentication is required for these images.

Can I somehow achieve that even in these scenarios the tokens are refreshed correctly before loading the image?

CodePudding user response:

You can use axios to fetch images as well. It looks something like this:

const url = "/media/cache/img.jpg";
const [objectURL, setObjectURL] = useState("");

useEffect(() => {
  axios
    .get(url, {
      responseType: "blob",
    })
    .then((res) => {
      const new_blob = new Blob([res.data], { type: "image/jpg" });
      setObjectURL(URL.createObjectURL(new_blob));
    });
}, []);


<img src={objectURL} alt={row.id} width={45} height={45}>

Now you can modify this to use your "interceptor for API calls" to refresh your token.

  •  Tags:  
  • Related