-2

I am trying to upload a file through the external API. I can retrieve the upload server URL with an API call. Now I need to send the file to it. API docs says I must send a POST request with the file. But my request is being blocked by CORS. I am sending it like this:

var request = new XMLHttpRequest();
request.open('POST', data["response"]["upload_url"], true);
request.overrideMimeType("multipart/form-data")

request.onload = function () {
    // ...
};

request.send({"file": f});

How do I properly send the request?

maximxls
  • 47
  • 1
  • 4
  • You need to provide more information about your server, your client code, and server code. Or, you can [read about CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) – Rojo Apr 10 '21 at 13:08
  • @Rojo API is external, not mine. I edited the question to make this clear. – maximxls Apr 10 '21 at 13:25
  • If you’re running into CORS issues, it’s more likely that the provider of the API in question did not intend for it to be leveraged in a browser-based context. – esqew Apr 10 '21 at 13:38
  • If the external API doesn't give you permission to use it via CORS then you can't use it from the client-side code. – Quentin Apr 10 '21 at 13:39
  • That said, aside from your CORS issue, your JS is completely wrong for uploading files. You can't pass a simple object to the send method and `overrideMimeType` is for overriding the mime type on the **response** so you can parse the *response* differently. – Quentin Apr 10 '21 at 13:39

1 Answers1

-2

I'd use fetch to send request, the body should be an instance of FormData

 var form = new FormData();
 form.append('file', f);

 fetch('upload-url', {
    method: 'POST', 
    body: form
 }).then(function(res){
    console.log(res)
 }).catch(function(err){
    console.log(err)
 })
Salma
  • 42
  • 1
  • 5
  • 1
    This answer would greatly benefit from an explanation of how this works around the OP’s current CORS issues (I’m not sure it does). – esqew Apr 10 '21 at 13:37
  • @esqew before, I was sending content-type header set to multipart/form-data, and I had cors problem, when I eliminated the content-type header, it worked just fine. – Salma Apr 10 '21 at 13:49