therochvoices
therochvoices

Reputation: 91

XMLHttpRequest not being able to make a request to Flask server

I have setup a simple flask server using the following code:

from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
    return "Hello, cross-origin-world!"

if __name__ == '__main__':
    app.run(host = '0.0.0.0', port='5000')

From js I am making a request to the address using the follwing code

const theUrl="<myip>:5000/";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false); 
xmlHttp.send();
console.log(xmlHttp.response);

The console shows

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>

When I try to access the same url from the browser, it returns

Hello, cross-origin-world!

Is there something wrong I am doing with the server? I have tried the js code on a dummy address and I am able to get the contents of that website. There is something wrong with the Flask server.

Upvotes: 1

Views: 2591

Answers (1)

Swift
Swift

Reputation: 1711

Just wrote something for file uploads.

Hope this helps.

$('.custom-file-input').change(function () {
    console.log($(this)[0].files[0].name);
    $('.custom-file-label').text($(this)[0].files[0].name);
    var formData = new FormData();
    formData.append('file', $(this)[0].files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/', true);
    xhr.send(formData)

I don't understand why one would use XHR for get requests, couldn't you just use Ajax instead?

The last parameter is whether the connection is asynchronous. Perhaps that's what wrong?

Also, don't use Flask built-in webserver for production environment, it just isn't made to cope with more than one user testing for example.

Furthermore, perhaps someone can tell me why not, however, I think you would be better off simply having url as the section of the url after the port declaration, in my example, notice that I only tell jquery or js to post data to / and this is because that means local server, or is interpreted to mean itself, so by default is prepended with your server IP and in this case the port 5000 aswell

Upvotes: 1

Related Questions