malioboro
malioboro

Reputation: 3281

Can't Get Json from Flask Rest API using getJSON

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?

Upvotes: 2

Views: 1364

Answers (2)

Andrew Fan
Andrew Fan

Reputation: 304

  • 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.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599600

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.

Upvotes: 0

Related Questions