0

I have created an api that receives a post from a form from a separate domain. When I use POSTMAN in the Headers section

Content-Type:application/x-www-form-urlencoded
X-Requested-With:XMLHttpRequest

And it works when I add in the POST values. But when I add it to production server ajax:

$.ajax({
    type: "POST",
    headers: {"Content-Type": "application/x-www-form-urlencoded","X-Requested-With": "XMLHttpRequest","Access-Control-Request-Headers": "*","Access-Control-Request-Method": "*"},        
    url: "https://sample/test/t/start",
    data: frmData
}).done(function (data) {
    console.log(data);
});

// XMLHttpRequest preflight request
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://sample/test/t/start", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function () {
    console.log(xhr.responseText);
};
xhr.send();

// Fetch preflight request
var myHeaders = new Headers();
myHeaders.append("X-Requested-With", "XMLHttpRequest");
fetch("https://sample/test/t/start", {
    headers: myHeaders
}).then(function (response) {
    return response.json();
}).then(function (json) {
    console.log(json);
});

These are the Errors from the above I get

Access to XMLHttpRequest at 'https://sample/test/t/start' from origin 'https://otherdomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Access to fetch at 'https://sample/test/t/start' from origin 'https://otherdomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  • Unless you change the type, jQuery defaults to form encoded. You do not have to set it. Ref. http://api.jquery.com/jQuery.ajax/ under `contentType` – Taplar Dec 03 '18 at 21:03
  • Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – Taplar Dec 03 '18 at 21:06
  • do you have csrf set up properly for the ajax route? – korwalskiy Dec 03 '18 at 22:16

0 Answers0