How to discard preflight response in AngularJS

2019-06-26 08:06发布

When sending a http.post request to my service I initially send an Option request (as required by Cors).

However I've realized that my OPTIONS (pre-flight) request is returning no response.data in its response, but my POST request is. This poses a problem as I need to access the response.data from the POST response...

Does Angular allow us to somehow discard the OPTIONS response in a http.post call?

$http.post("http://api.worksiteclouddev.com/RestfulAPI/api/vw_PeopleListSiteAccess_Update/Get/", JSON.stringify(vm.content))
    .then(function (response) {
        //success

        vm.person = {
            "firstname": response.data.Firstname,
            "surname": response.data.surname
        }; 
        console.log(response.data);
    },
    function (error) {
        //failure
        console.log("Something went wrong..." + error.status);
    })
    .finally(function () {
        vm.ptsnumber = "";
    });

Chrome responses: enter image description here

1条回答
爷的心禁止访问
2楼-- · 2019-06-26 08:34

You can't discard preflight OPTIONS request.

The purpose of this request is to ask the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

They are necessary when you're making requests across different origins.

This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.

In your case you should get the response here in post api response

$http.post(
 "http://api.worksiteclouddev.com/RestfulAPI/api/vw_PeopleListSiteAccess_Update/Get/", JSON.stringify(vm.content)
).then(function (response) {
  console.log(response.data);
  //You should get your response here
},
function (error) {
  console.log("Something went wrong..." + error.status);
});

//For more you can create external service and call api in that service
//in you controller you can call that method

查看更多
登录 后发表回答