1

I am studying about RESTful APIs and I decided to create a small server and a consumer to test.

I'm using Flask as a server and an example I took on the internet to consume this API. But I'm having some problems.

The error message on the console says this: XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

But I do not know what it can be.

Flask server code:

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id':1,
        'title': u'Estudo',
        'description': u'Sistemas Distribuidos',
        'done':True
    },
    {
        'id':2,
        'title': u'Monitoria',
        'description': u'Programacao e Algoritmos',
        'done': False
    }
]


@app.route('/')
def index():
    return "URL PARA O ACESSO DA API: '/api/tasks'"

@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

Example code using Jquery:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>Mashape Query</title>
  <script>
    function doIt() { 
 var output = $.ajax({
    url: 'http://127.0.0.1:5000/api/tasks', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
    data: {}, // Additional parameters here
    dataType: 'json',
    success: function(data) {
        //console.log(data);
        alert(data);
        document.getElementById("output").innerHTML = data.source; 
        },
    error: function(err) { alert(err.getText); }
});


}

</script>
</head>
<body>

  <button onclick="doIt()">Run the request</button>
  <div id="output">The API request is:</div>

</body>
</html>
mdcg
  • 65
  • 8

1 Answers1

0

Most likely the easiest is to install https://flask-cors.readthedocs.io/en/latest/.

From their Simple Usage guide:

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

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

If you don't want to install another package, you can try to use the solution from here https://stackoverflow.com/a/33091782/2525104 by Salvador Dali.

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Kenjin
  • 136
  • 1
  • 4