AngularJS Sends OPTIONS request instead of POST

早过忘川 提交于 2019-12-21 03:29:26

问题


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




回答3:


Server will check either you should be allow to post some data on server itself or not as per the

cross origin resource sharing policy

that is quite normal that you are getting options request. your ApI server should have configured to allow request from your domain to work correctly.



来源:https://stackoverflow.com/questions/22346408/angularjs-sends-options-request-instead-of-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!