0

I've hosted a python flask api on pythonanywhere. It takes json input, performs some operations and returns response in json format.

I've a website that tries to call this API and should display the response.

Button click calls a javascript function apicall().

HTML code:

<button type="submit" name = "submit" id = "submit" onclick="apicall()">Check</button>
<label id="response"></label>

Javascript Function (It tries to set the label text to the response text):

<script type="text/javascript">
function apicall(){ 

  xmlObj = new XMLHttpRequest(); //suddenly global scope
  xmlObj.open("POST","http://abc.pythonanywhere.com/xyz",true);
  xmlObj.setRequestHeader("Content-Type", "application/json");
  var website=document.getElementById("url").value;
  var data = JSON.stringify({"url": website});
  xmlObj.send(data);
  xmlObj.onreadystatechange = handleRequestStateChange();
  function handleRequestStateChange(){  
  alert("here");
  if(xmlObj.readyState == 4 && xmlObj.status==200){
    var json = JSON.parse(xmlObj.responseText);
    document.getElementById("response").innerHTML =json.prediction;
    alert("if loaded");
  }
  else
  {
      alert(xmlObj.status);
  }
 }
}
</script>

However, it alerts status 0.

Error printed on console says: "[CORS]The origin did not find the origin in the access-control-allow-origin in the request header for cross-origin resource at http://abc.pythonanywhere.com/xyz"

Network Tab in developer tools shows the connection to python anywhere and response code of 200[ok]

Referred links:

Why is AJAX returning HTTP status code 0?

XMLHttpRequest status 0 (responseText is empty)

But was not able to solve the issue

I also tried jquery to do the same thing

<script>
        $(document).ready( function() {
        $('#submit').click(function() {
           var website=document.getElementById("url").value;
           $.ajax({
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(website),
                dataType: 'json',
                url: 'http://abc.pythonanywhere.com/xyz',
                success: function (e) {
                   alert(e);
                   console.log(e);
                   window.location = "https://www.google.com"
                },
                error: function(error) {
                console.log(error);
            }
            });
        });
  });
</script>

But the jquery code just reloads the page when I click that button with no errors anywhere(or maybe the error log and network log just clears up because of reload).

How can I allow the cross origin requests on python API or how do change the code in javascript or jquery to make this thing work?

1 Answers1

1

I was able to solve this issue by adding the following lines to python rest API.

pip install -U flask-cors

from flask_cors import CORS
cors = CORS(app)