Reputation: 147
I am trying to get image data uri through image url using the function below, however, I kept getting a cross origin error even though the image is stored in the localhost folder. Can anyone help me with this?
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
var imageAttribute = {
dataUrl: dataURL,
height: canvas.height,
width: canvas.width
};
if (callback) callback(imageAttribute, options);
};
img.src = url;
console.log(img.src);
The code throws cross origin issue on the line img.src = url
as it tries to hit my localhost url.
Below is the error that is shown in the console.
Access to image at 'https://localhost:44377//Data/files/logo-rs.png' from origin 'https://localhost:44376' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Upvotes: 2
Views: 3002
Reputation: 184
An origin is a domain, plus a scheme and port number.
you use two different port 44376 and 44377
44376 only access to 44377 when on the header of 44377 response was something like this
Access-Control-Allow-Origin: https://localhost:44376
and how to add this header to your responses, it depends on your server
you can see Apache, IIS6, IIS7, PHP and ASP.NET in
https://www.aurigma.com/docs/us8/enabling-cross-origin-resource-sharing.htm
NodeJS in
How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js
XAMPP in
How do I enable cross-origin resource sharing on XAMPP?
Good luck ☺
Upvotes: 1