user9413053
user9413053

Reputation:

Cross-Origin Request Blocked At time of sending post request

I have 2 servers and 2 domains I want to send a post request from one domain to another but my browser shows an error

access to XMLHttpRequest at 'https://example.com' from origin 'https://www.example2.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

the javascript code i am using To send Post Data is

<script>
var data = JSON.stringify({
  "key": "value sent"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});
xhr.open("POST", "https://example.com");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
</script>

So My question is how I can resolve this problem and send a Post request to another domain and which method to use to send post request

Upvotes: 2

Views: 8384

Answers (1)

Łukasz Blaszyński
Łukasz Blaszyński

Reputation: 1565

You need to enable CORS on your server. In case of NodJs you can do something like this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/', function(req, res, next) {
  // request from other domain will work here
});

in browser use

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

Upvotes: 3

Related Questions