Download Image Using Fetch In ReactJs - javascript

I'm trying to download an image using fetch in reactJS. But whenever I call the function, I face the CORS error.
var image_trade_license = new Image();
image_trade_license.crossOrigin = "anonymous";
image_trade_license.src = "https://via.placeholder.com/150/92c952";
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually
var fileName_trade_license = 'trade_license';
image_trade_license.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob_trade_license;
// ... get as Data URI
if (image_trade_license.src.indexOf(".jpg") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/jpeg");
} else if (image_trade_license.src.indexOf(".png") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/png");
} else if (image_trade_license.src.indexOf(".gif") > -1) {
blob_trade_license = canvas.toDataURL("image_trade_license/gif");
} else {
blob_trade_license = canvas.toDataURL("image_trade_license/png");
}
$("#image1").append("<a download='" + fileName_trade_license + "' href='" + blob_trade_license + "'><button>Download Trade License</button></a>");
}
and I am facing this error (occured in browser Console) -
Access to image at 'https://via.placeholder.com/150/92c952' from origin
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-
Allow-Origin' header is present on the requested resource.
via.placeholder.com/150/92c952:1 Failed to load resource: net::ERR_FAILED

First, Have you ever set mode: "no-cors" in fetch config? Like this:
fetch('https://via.placeholder.com/150/92c952', {
method: 'POST',
mode: "no-cors"
})
If you still receive CORS error. You can disable origin policy in Chrome to continue to call API that without CORS error with This Post
Or, This post could give you more knowledge about CORS in Web Browser.

Related

"blocked by CORS policy" error, Take input locally rather than webcam in teachable machine code

From the teachable machine export, I copied javascript code and it takes its input from the webcam to give produced results. I want to provide an input image from my device but facing an issue as my code is not giving any output.
This is my code
<div>Teachable Machine Image Model</div>
<button type="button" onclick="init()">Start</button>
<div id="label-container"></div>
<!-- Add the file input element -->
<input type="file" id="file-input" accept="image/*"/>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.3.1/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#teachablemachine/image#0.8/dist/teachablemachine-image.min.js"></script>
<script type="text/javascript">
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/Kk5_BUYCy/";
let model, fileInput, labelContainer, maxPredictions;
// Load the image model and setup the file input element
async function init() {
console.log("inside init")
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Replace the webcam object with the file input element
// webcam = new tmImage.Webcam(200, 200, flip);
fileInput = document.getElementById("file-input")
fileInput.addEventListener("change", predict(fileInput));
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
async function predict(fileInput) {
console.log("inside predict")
try {
// Get the file from the file input element
const file = fileInput.files[0];
// Load the image
const image = await tmImage.load(URL + file);
// Predict the class
const prediction = await model.predict(fileinput);
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
} catch (error) {
console.log(error)
}
}
</script>
Getting error:
Access to fetch at 'https://teachablemachine.withgoogle.com/models/Kk5_BUYCy/%5Bobject%20File%5D' from origin 'http://127.0.0.1:5500' 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.

GoogleDrive API (javascript): no file download because of CORS

With this code, before an year about i could get the file via XMLHttpsRequest.
Now this do not more work, because of the error:
Access to XMLHttpRequest at 'https://drive.google.com/uc?id=1zGxNBh-YTAXu74v855l2b_LPmLUaomqZ&export=download' from origin 'https://encrypt.pdfzorro.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Is there a way at now, to get the file via javascript. I can not use any server solution, the file should go direct from googleDrive to the browser from the user.. without go on a server (with php e.g.) first.
function downloadFileContent(fileId){
gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'method': 'GET',
callback: function ( theResponseJS, theResponseTXT ) {
var myToken = gapi.auth.getToken();
var myXHR = new XMLHttpRequest();
myXHR.open('GET', theResponseJS.downloadUrl, true );
myXHR.responseType = 'arraybuffer';
myXHR.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token );
myXHR.onreadystatechange = function( theProgressEvent ) {
if (myXHR.readyState == 4) {
// 1=connection ok, 2=Request received, 3=running, 4=terminated
if ( myXHR.status == 200 ) {
// 200=OK
cossole.log(myXHR.response);
}
}
}
myXHR.send();
}
});
}

Failed cross domain xml Get Request

Im trying to help a friend out with a program but my coding experience is somewhat dated (10 years give or take). Where trying to pull data from a database via their API. Im making this request via a XMLhttpRequest but im having issues even getting to the Server.
The error that occurs:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/jasper/api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477
Its trying to search for the url on my own domain. But I need it to search cross domain.
The entire function:
function getRequest(){
var _request = new XMLHttpRequest();
var key = myKeyHere;
var url = "api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/JSON", false);
_request.setRequestHeader("Content-Type", "application/JSON", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
I've also read a lot about CORS and how this affects these kinds of requests cross domain, but i don't quite understand how it works and how i can work arround it.
Any help is appreciated.
First of all you need to prefix your URL with https://. This way you make a request to the external server instead of localhost. The second thing is that in your headers the application/JSON should be application/json.
Also dont forget that your key needs to be prefixed with "API". Example API [some_random_key]
I've tested the following code and it worked. You just have to add your own API KEY.
function getRequest(){
var _request = new XMLHttpRequest();
var key = "API [replace_this_with_your_key]"; // Example: "API a1b2c3d4e5f6g7h8i9"
var url = "https://api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/json", false);
_request.setRequestHeader("Content-Type", "application/json", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
Try to add // at the start of the line in url variable declaration (line 4), if you want to make a request to the external server.
Your request was made to the local webserver http://localhost/jasper/... and you've received a 404 (not found) error.

Download Google Drive file from url and send with post to backend

I am trying to download a file from an url (chrome drive file) in javascript; and want to send it to my backend (php - laravel).
var url = file.downloadUrl !== undefined ? file.webContentLink : file.exportLinks['application/pdf'];
console.log(url) // if I go to url, it downloads the file
if (url !== undefined) {
var remote = new XMLHttpRequest();
remote.open('GET', url);
remote.setRequestHeader('Authorization', 'Bearer ' + gapi.client.getToken().access_token);
remote.setRequestHeader('Access-Control-Allow-Origin', '*');
remote.onload = function(e) {
vm.handle_download(remote.responseText, file, 200); // do something with the fetched content;
};
remote.onerror = function(e) {
vm.handle_download('error response', null, remote.statusText);
};
remote.send();
} else vm.handle_download('no downloadable url', {
file: null,
status: 'error'
});
and on handle
handle_download: function (content, file, status) {
if (status !== 200) {
console.log('error occured on status')
return;
}
}
Failed to load https://drive.google.com/uc?id=1D12321ofd4CNG-m9_Mp4aiDcnibNf&export=download: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.dev' is therefore not allowed access.
This is an intended behavior due to same origin policy in the web. Since you're doing this for testing purposes, try this Allow-Control-Allow-Origin chrome extension.
You can read more about how to implement this in Using CORS tutorial.
This SO post may also offer additional insight.

Parse.com - Cross-Origin Request Blocked

I'm new to parse and javascript. i'm going through a very simple tutorial at Parse.com (https://parse.com/apps/quickstart#parse_data/web/new) and created the following block of code. It works on chrome and IE but not safari or firefox. I got the cross-origin request blocked error on firefox. Could you please help?
Firefox Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.parse.com/1/classes/things.
This can be fixed by moving the resource to the same domain or enabling CORS.
My Code:
var PARSE_APP = "XXX";
var PARSE_JS = "XXX";
$(document).ready(function () {
Parse.initialize(PARSE_APP, PARSE_JS);
$("#FinishQuiz").click(function () {
var ShoulderStrap = "";
if ($("#ShoulderStrap1").prop("checked"))
{ ShoulderStrap = "1" }
if ($("#ShoulderStrap2").prop("checked"))
{ ShoulderStrap = "2" }
if ($("#ShoulderStrap3").prop("checked"))
{ ShoulderStrap = "3" }
NoteObject = Parse.Object.extend("things");
var object = new NoteObject();
object.save({ ShoulderStrap: ShoulderStrap }).then(function (object) {
alert("yay! it worked");
});
});

Categories

Resources