Javascript request results in undefined when using Flask - javascript

I've spent hours messing around with this... and I don't understand why I'm getting an undefined response when I use Javascript to make a request. My flask app is extremely basic and looks like the following:
#app.route('/timespent', methods=['GET', 'POST'])
def calculateAvgReadTime():
return jsonify({'result':'Success'})
The Javascript code I'm using to make a request to this endpoint is the following:
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
console.log(xhr.status)
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process our return data
if (xhr.status >= 200 && xhr.status < 300) {
// What do when the request is successful
console.log(JSON.parse(xhr.responseText));
}
};
xhr.open('GET', 'https://xxxxx.herokuapp.com/timespent');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
What's confusing is the following:
if I use Python or software like Insomnia, then the request is returned as expected and nothing is wrong - this is what makes me think something is wrong with the Javascript...
When I change the URL in the Javascript to "https://jsonplaceholder.typicode.com/todos/1", it works as expected and returns a json - this is what makes me think that my flask app is wrong...
Some help would be greatly appreciated.

Related

"request sent by the client was syntactically incorrect" when making REST call to Jira

I'm using HTML macros in confluence to automate some tasks in Jira. I tried the following REST call in the code below to add a comment to a ticket and I get the error: 400: Bad Request. The request sent by the client was syntactically incorrect.
I can't see any issues with my JSON or code. This pretty much fails for other operations I've tried such as creating/updating tickets.
xmlhttp = new XMLHttpRequest();
var url = "http://<CONFLUENCEURL>.com:8090/plugins/servlet/applinks/proxy?appId=<APPID>&path=http://<JIRAURL>:8080/rest/api/2/issue/TEST-3/comment";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}else{
console.log(xmlhttp.responseText);
}
}
var parameters = {
"body" : "Hello world!"
};
function addComment() {
xmlhttp.send(JSON.stringify(parameters));
}
I eventually created an identically ordered JSON object, turns out that the parser the server side uses does not follow the JSON specification in that it expects the correct order.
As in, the fix would be to follow the JSON specification server side, or replicate identically the structures being sent to the server.

Parse Error from JS AJAX requests only on live server - Python GAE

I have a number of AJAX requests (made with regular JS) that seem to be causing trouble when they make requests of my Python GAE back end. Here's an example:
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.send(JSON.stringify(requestOjb));
},
I am getting a code 400 with a Parse Error, but only on my deployed server. Everything works fine on the dev server. The error says the problem is with my back-end function "new_game", but does not specify a line where the error occurred. The endpoint function works correctly when I access it directly from the API explorer, so I figure the problem must be a result of the data sent from my JS file. Here's that function anyway:
#endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# ... removed unnecessary code for this question
return game.to_form('Good luck playing Battleship!')
The request message it's expecting takes the form of {'user_name': 'some_name'} and it appears, through console.log, that JS is sending it in the right format.
The log where the parse error comes up is interesting, because it shows a 200 code POST request, although it mentions the 400 error when I dive into that log.
I've double and triple checked that my code works on the dev server, and that I've got the exact same code deployed. I don't know where to look next to continue debugging this thing. Any help is appreciated.
Figured it out. I tried running the AJAX request with jQuery, and got a slightly different error message, which lead me to find that I had to set the request header, because it was causing the server to read the incoming data differently than it should have. The following AJAX request now works perfectly.
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(requestOjb));
},

Check if a remote JSON is newer than the local one without download the entire file in Javascript

I'm creating a Phonegap app that check if a local JSON is up to date comparing it with the last Remote version of it. If the remote version is newer than the local the program will update the local JSON.
To avoid bandwith waste I would like to do the version check without downloading the whole remote data. Just checking the headers... I guess...
Looking for a solution I found that some people talk about "HTTP ETag header" like in this thread
Does somebody know How could I implement something like that in pure Javascript?
Thanks in advance.
If your server sends the correct response type of
304 - Not modified you can check for an update with something like this
function hasUpdate(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status === 200) {
// Data is new -- maybe do another request and grab a copy?
} else if (this.status === 304) {
// Data is not modified
} else {
// Something else happened.
}
}
};
http.send();
}

Simple code for request url and show response code | javascript | jquery

How can to request url or website address and show response code with javascript or jquery?
i.e
request www.google.com
if (response_code = 200) {
print "website alive"
} else if (response_code = 204) {
print "not found";
}
I'm assuming from the jquery tag that you mean to do this in a browser, not from a server running NodeJS or similar (although there is a NodeJS module for jQuery).
Although you can request URLs and see the response code using the XMLHttpRequest object, the Same Origin Policy will prevent your accessing virtually any sites other than the one the page itself was loaded from. But if you're pinging the server your page was loaded from to make sure it's still there, you can do that:
function ping(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("get", url);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) { // Request is complete
callback(xhr.status); // Tell the callback what the status code is
}
}
}

XMLHttpRequest: POST request status

I have such part of code:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://someurl.com", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
doSomeTask();
}
}
}
xhr.send('login=mylogin&password=mypassword');
How can I know if my login&password are correct? In both cases xhr.status is 200.
Invalid Login/Password attempts are not HTTP failures. Only HTTP Failures return you 4xx or 5xx return codes. You might want to use the xhr.responseText or xhr.responseXML from the response to see what your backend is returning and base your decision according to that. Please refer to http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#dfn-responsetext for how the responses are obtained.
Also, there are tons of good Javascript framework that hide the complexity of making Ajax calls. JQuery makes the job of calling AJAX scripts extremely easy. You might want to investigate on that instead of writing raw XHR code.

Categories