I'm in the process of converting an $.ajax calls to use fetch instead.
I have a PUT call that resembles this (this is an upload of a file from an html form, assume that the "file" object exists and is correct):
const formDataObj = new FormData();
formDataObj.append("file", file, 'test.png');
const settings:any = {
"url": "https://somedomain.com/upload",
"method": "PUT",
"timeout": 0,
"headers": {
"Authorization": `Bearer ${token}`
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": formDataObj
}
const result = await $.ajax(settings);
In this case, the "result" shows exactly the result that I would expect. In other words, using jQuery to perform this PUT operation works perfectly. The "result" object contains the correct response from the server, which is a string version of a JSON object.
However, when I attempt to do the same using fetch, it does not work. Here's what I attempted:
const formDataObj = new FormData();
formDataObj.append("file", file, 'test.png');
const settings:any = {
"method": "PUT",
"timeout": 0,
"headers": {
"Authorization": `Bearer ${token}`
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": formDataObj
}
const response = await fetch('https://somedomain.com/upload', settings);
const data = await response.json();
The "fetch" version shows this error:
Access to fetch at 'https://somedomain.com/upload' from origin 'https://someotherdomain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Since the response from the server is JSON represented as a string, not a JSON object, I was thinking that this might be the issue. Or, maybe these libraries treat the "data" property differently?
Since the $.ajax call works exactly was it should, I assume that this is not actually a CORS issue.