Cross origin issue with cropper.js

4.2k views Asked by At

I am using cropper.js to crop the images I wrote a directive which will take the image src

return {
        restrict: 'A',
        controller: _cropperController,
        bindToController: {
            imagesrc:"=?"
        },
        link:function($scope, $element, $attrs, ctrl){
            var img = document.createElement("img");
            img.src = ctrl.imagesrc;
            img.id='image';
            document.getElementsByTagName("body")[0].appendChild(img);
            Cropper.setDefaults({
                checkCrossOrigin: false
            });
            var cropper = new Cropper(img, {
                aspectRatio: 1 / 1,
                checkCrossOrigin: false,
                crop: function(e) {
                    console.log(e.detail.x);
                    console.log(e.detail.y);
                }
            });
            if(cropper.getCroppedCanvas()){
                var imgurl =  cropper.getCroppedCanvas().toDataURL();
                ctrl.imagesrc= imgurl;
            }

        }
    };

Then create the image element, append it to dom and them pass the image to the cropper constructor

I have set default options checkCrossOrigin to false but still giving the error

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9090' is therefore not allowed access.

Any help would be appreciated.

2

There are 2 answers

0
Chodmal Choudhary On

Take an example of chrome extensions. If we place our author URL in permissible URL's then Cross module calls will not be stopped.

Otherwise it will always go as OPTIONS instead of POST/GET.

0
Juvenik On

Whenever any client makes a request to the server, then the protocol, domain and port of the client and the server must be the same. If any of these attributes are different then we get Cross Origin Issue.

The fix cannot be made at the client's site but has to be made in the server side. At the server, you need to make sure that request from all the sites are accepted. We need to make changes to the header of a response.

I am using Vertx as a server and this is how I am handling the response for Cross Origin

routingContext.response().putHeader("content-type", "application/json")
      .putHeader("Access-Control-Allow-Origin", "*")
      .putHeader("Access-Control-Allow-Headers", "Content-Type")
      .putHeader("Access-Control-Allow-Headers", "Authorization")
      .putHeader("Access-Control-Allow-Methods", "GET, POST, PUT , OPTIONS");

Please don't bang your head try to fix it from Client's side as it cannot be done. I spent lot of time when i was not aware of it.

Thanks.