2

I am trying to send a HTTP request in javascript using XMLHttpRequest and so I am using the following code in an HTML file. I have a server running which returns a dictionary of form {'test' : 'string'}.

<script type="text/javascript">
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://localhost:5000/test", true);
  xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
  xhr.send();

  xhr.onreadystatechange = processRequest;
  console.log(xhr.status)

  function processRequest(e)
  {
    if (xhr.readyState == 4)
    {
      alert(xhr.responseText);
    }
  }
</script>

However in spite of adding the header, I am getting a Cross-Origin Request Blocked: error in my console when I try to print xhr.status in the console it shows 0 as response. I am using flask server which shows a bad message error on using HTTPS, so I am using an HTTP request.

3
  • Is the page that this script is running on, also hosted on http://localhost:5000/? Commented Jun 13, 2016 at 9:03
  • No, Its a separate HTML file through which I want to send a HTTP request. Commented Jun 13, 2016 at 9:09
  • That is the problem, read about why it is blocked, maybe here. You cannot set the Access-Control-Allow-Origin header on the client side. This needs to be set up on the server, i.e. the server should allow you to connect to other domain(s). Commented Jun 13, 2016 at 9:27

1 Answer 1

1

You can not control CORS from front end. You have to put the CORS module to your back end server.

check the link flask cors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.