2

I am new in Javascript and I get the following problem. So I make a simple Flask API return a simple json

Flask code:

from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/test')
def test():
    return jsonify({"result":"wt is works!"})

if __name__=="__main__":
    app.run()

I run it using gunicorn -k gevent -w 5 main:app and when I check localhost:8000/test in browser it returns the json normally

But when I try to get it using Jquery it return nothing. My HTML didn't get any value from localhost:8000/test

My current html code:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type=text/javascript>
            $(document).ready(function(){
                $.getJSON(
                    "http://localhost:8000/test",
                    {format: "json"})
                    .done(
                        function(data) {
                            var plot_id = data.result;
                            $("#retval").html( "<strong>" + plot_id + "</strong>" );
                        }
                    );
            });
        </script>
    </head>
    <body>
        <div id="retval"></div>
    </body>
</html>

But when I change the url and try to get data from another API, let say from https://jsonplaceholder.typicode.com/posts/1 it works.

I've tried solution from:

but it still doesn't work, can somebody help me please to find out what is the problem?

malioboro
  • 3,097
  • 4
  • 35
  • 55

2 Answers2

1
  • Define the port to be used as server port: app.run(host='0.0.0.0', port=8000)
  • More important,the way browser get localhost:8000/test between your function getJSON or ajax are different. It has a problem about 'access-control-allow-origin'. In flask, you could use the package flask-CORS to get the job done.
Andrew Fan
  • 274
  • 2
  • 6
0

You have a few errors in your JS.

Most obviously, you are requesting an invalid URL. 0.0.0.0 is an interface you can bind your server to, but it is not a URL you can request. Use localhost or 192.168.0.1.

I would say thay the other main error is that there is no comma between the URL and the following options object, but in fact getJSON does not take an options parameter. Remove that object altogether.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • oh sorry about the url, I've mixed my code. I've change it to localhost and put a comma. But It still doesn't work. And what should I remove? the `format`? I've just tried to remove it and it still doesn't work – malioboro Aug 29 '17 at 07:32
  • I've updated my code fixing the `localhost` and a comma – malioboro Aug 29 '17 at 07:41
  • You need to do some debugging. Is the request being made to your Flask app at all? Can you see it either in the browser debugging tools or in the Flask console itself? If so, what is being returned? – Daniel Roseman Aug 29 '17 at 08:25