Home > Net >  How to send preflight request from axios of ReactJS
How to send preflight request from axios of ReactJS

Time:11-13

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

CodePudding user response:

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.

CodePudding user response:

Axios automatically send preflight OPTIONS request. Check the network tab

  • Related