PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to download image in react using axios?

 October 13, 2022     axios, download, image, node.js, reactjs     No comments   

Issue

My code and request is like this :

async function download(e, siswa) {
console.log(siswa)
e.preventDefault();
await axios({
  url: `${process.env.REACT_APP_API_KEY}public/images/${siswa.siswa_gambar}`,
  method: 'GET',
  responseType: 'blob',
}).then(res => {
  console.log(res)
  const url = window.URL.createObjectURL(new Blob([res.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', siswa.siswa_gambar);
  document.body.appendChild(link);
  link.click();
})

But i keep getting cors error even tho i've set cors option to "*"

const corsOptions = {
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true
};
app.use(cors(corsOptions));

like so, what should i do?


Solution

CORS Should Always Be Handled From Server Side!

You don't have to handle it from the front-end, ensure that your backend team has pass the CORS headers inside their request then you will get rid of this error. In the backend set the request's mode to 'no-cors' to fetch the resource with CORS disabled. It states that there's a missing Access-Control-Allow-Origin header on the resource you requested. If you think about it, your client doesn't have anything to do with CORS so it should always be handle from the server side



Answered By - Wasiq Ali
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing