Search code examples
javascriptrestpostherokuflask

Flask App Javascript not working from localhost but works from 127.0.0.1


My application server: python+flask UI: html + javascript with callback and POST method

Application runs fine with redirection, rest api call etc at: http://127.0.0.1:5000/ When Submit button is clicked, nothing happens from: http://localhost:5000/ Also nothing happens from: http://finhelper.herokuapp.com/ <-- html + java scripts can be read here

I think none of the Javascripts are working for some reason when running without 127.0.0.1. CSS and separate pages work though.

EDIT:

the below javascripts are taking me to: http://127.0.0.1:5000/approve Which is same as: http://finhelper.herokuapp.com/approve

This redirection is not working from Heroku.

	<script type="text/javascript">

		function Submit(callback) {
			//url = 'http://finhelper.herokuapp.com/api';
			url = '/api';
			ItemJSON = '[  {"Married": 0,"Education": 0,"ApplicantIncome": 5000,"CoapplicantIncome": 1100,"LoanAmount": 150,"Credit_History": 1}]';
			//alert(url);
			var xhttp;
			var l_redir ='/';
			xhttp=new XMLHttpRequest();
			xhttp.onreadystatechange = function() {
				if (this.readyState == 4 && this.status == 200) {
					//alert('in this');
					myFunction(this);
					
				}
			};
			xhttp.open("POST", url, true);
			xhttp.setRequestHeader("Content-type", "application/json");
			xhttp.send(ItemJSON);
			//alert('sent REST call');
			window.location.href = l_redir; //not being used
			return false;
		}
		function myFunction(xhttp) {       //Callback function
			//alert('in callback');
			retval = xhttp.responseText;
			//alert(retval);
			var redir = '-';
			
			if (retval.includes("approved")) {
				redir = "/approve";
			} else {
				redir = "/reject";
			}
			//alert(redir);
			redirect(redir);               //Final redirection depending upon ML Return value
		}
		function redirect(redir) {
			window.location.href = redir;
			return false;
		}
	</script>

2nd EDIT: I can access this POST api that is running on same app.py from CURL but not from Javascript. Hence not getting httpResponse, identified using alert(). Any reason or suggestions please?

curl http://finhelper.herokuapp.com/api -k -X POST -H "Content-Type: application/json" -d "[{\"Married\": 0,\"Education\": 0,\"ApplicantIncome\": 5000,\"CoapplicantIncome\": 1100,\"LoanAmount\": 150,\"Credit_History\": 1}]"


Solution

  • I added alert() at almost each step of the javascript. It turned out, on Heroku, python REST app was taking bit longer time and hence asynchronous ajax call was timing out.

    For now I have added some delay but ideal way would be to implement below: Need a delay function javascript