简体   繁体   中英

Ajax post method not working shows status code 400

My ajax code for is not working. it shows error

XMLHttpRequest cannot load http://xxx.xxx.xxx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 400.

How to solve the problem. I have tried the different headers. But not posting the data. Please to solve my issue. my code is

$http({
       method: "post",
       dataType:'json',
        url: res,
       crossDomain : true,
        data: {
            'name': $scope.name,
            'email': $scope.email,
             'text area': $scope.query

        },
headers: { 'Access-Control-Allow-Origin': '*' }
    }).then(function success(data) {


        alert("Message sent succesfully");
        /*var success=data.data.issuccess;
        if(success==true)
        {
          var name=data.data.username;
          var userid=data.data.userid;
          alert("Name= "+name+ "UserId="+userid);
        }*/




    });

It's working postman as correct. but not in ajax. 在此处输入图片说明

You have to enable CORS on the server.

Please read this:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Also check this one:

https://enable-cors.org/server.html

Note: I am correcting this after reading the comment from SLaks. He is correct.

The problem is that http://xxx.xxx.xxx doesn't send the right header in its response for you to be able to access it. See https://fetch.spec.whatwg.org/#cors-protocol-examples for flow examples.

I have solve the problem. It is the problem face in server side. and i change the code is

$.ajax({
url: "http://xxx.xx.xx.xx/api/SendMail/SendEmail",
type: "POST",
async: false,
ContentType: "application/json; charset=utf-8",
data:  {
            'subject': "Contact us from SQU app",
            'message': msgSQU

        },
crossOrigin: true,
dataType: "json",
success: function (response) {
$resData = response;
//alert("Su");
showConfirm("Your Feedback succesfully send");


},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
//console.log(textStatus, errorThrown);
}
});

Now it is working as fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM