AngularJS Sends OPTIONS request instead of POST

2019-03-24 18:03发布

问题:

I'm trying to upload a picture to my S3 bucket. I'm using AngularJS v1.2.13. When I use the simple case as displayed in their docs (submit form with action tag) everything works fine. However, if I want to do it the Angular way with ng-click Angular sends an OPTIONS request instead of a POST request.

The following is the Service code, it first goes to the server to get a signature (I know that part is fine) then tries to POST with everything.

myServices.factory('s3', function($http) {
    var service = {};

    service.upload = function(fileName) {

        return $http(
            {
                method:"POST",
                url: "sign",
                data: { "fileName": fileName }
            }
        ).then(
            function(result) {
                // success
                //resolve the promise as the data
                var data = result.data;
                var url = "https://" + data.bucket + ".s3.amazonaws.com/";

                return $http.post(url, {
                    "key": data.key,
                    "AWSAccessKeyId": data.awsKey,
                    "acl": data.acl,
                    "policy": data.policy,
                    "signature": data.signature,
                    "Content-Type": "image/jpeg",
                    "success_action_redirect": "http://localhost:3000/s3Uploaded"
            }).then(
            function(response) {
                // success
                console.log("s3.upload, success: ");
                console.log(response);
            },
            function(response) { 
                // failed
                console.log("s3.Upload, fail: ");
                console.log(response);
            }
        );

    },
        function(response) { 
            // failed
            console.log("s3.sign, fail: ");
            console.log(response);
        }
    );
};

return service;
});

What am I doing wrong?

回答1:

In S3 headers in CORS add header:

Access-Control-Allow-Origin: *



回答2:

Angular is sending a preflight request, so if you can go back to your first plan, do that!

https://stackoverflow.com/a/44343635/1308736

https://stackoverflow.com/a/22968724/1308736