Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send preflight request from axios of ReactJS

curl -s -v --tlsv1.2 -H "Origin: http://localhost:3000" -F upfile=@_mat/myfile.mp3 -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: X-Requested-With" -X OPTIONS https://api.aicomposer.net:8008/upload

There is no axios.option thoughm, I made this code.

  formData.append(
    "upfile",
    this.state.selectedFile, // _mat/myfile.mp3 is stored from input type="file" here
    this.state.selectedFile.name // 
  );

  const config = {
    headers: {
      "Access-Control-Request-Headers": "X-Requested-With" ,
      "Access-Control-Request-Method": "POST",
      'Origin':"http://localhost:3000",
    }
  }
  axios.post(`https://api.example.com:8008/upload/`,formData,config).then((res) =>
  {
    console.log(res);
  }).catch(err =>{
      console.log(err);
  });

It shows many errors.....

Refused to set unsafe header "Access-Control-Request-Headers" Refused to set unsafe header "Access-Control-Request-Method" Refused to set unsafe header "Origin"

How can I make the equivalent code to curl??


THank you for comment.

I understood axios send preflight request automatically

However I still not unsure ,how it works.

For example I attached the header 'Content-Type': 'application/json' to GET request.

  var config = {
    headers: {
      'Content-Type': 'application/json'
    }
  }
  axios.get(`http://api.example.com/upload/`,config).then(res =>{
    console.log("upload endpoint get OK");
    console.log(res);
  }).catch(err=>{
    console.log("upload endpoint get NG");
    console.log(err);
  });

It doens't show error but,upload connection is called only once in google developper console.

enter image description here

like image 1000
whitebear Avatar asked Jan 24 '26 02:01

whitebear


2 Answers

Browser automatically will send preflight requests and cache the response based on the response's cache time. You can't set such headers for the sake of security reasons. Don't worry, the browser will handle them.

like image 141
MPCL5 Avatar answered Jan 26 '26 17:01

MPCL5


Ran into this yesterday and found that it’s a potential bug in v0.27.2 and possibly other versions: https://github.com/axios/axios/issues/4712. Going to try upgrading to latest today.

like image 41
Troy Lindsay Avatar answered Jan 26 '26 16:01

Troy Lindsay