No 'Access-Control-Allow-Origin' header is present on the requested resource (flask - python - js)

0


The following is the code I use to pick up the URL " link "
 (RESTful API - Python and Flask)

    from flask import Flask, request
    from flask_restful import Resource, Api
    from sqlalchemy import create_engine
    from json import dumps
    from flask_jsonpify import jsonify
    from flask_cors import CORS

    db_connect = create_engine('sqlite:///lite.db')
    app = Flask(__name__)
    api = Api(app)
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

    class Tracks(Resource):
        def get(self):
            conn = db_connect.connect()
            query = conn.execute("select trackid, name, composer, unitprice from tracks;")
            result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
            return jsonify(result)

    api.add_resource(Tracks, '/tracks') # Route_2

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

When I want to use the URL with the data I use d3js and in the console I get the message: (see image)

    <!DOCTYPE html>
    <html>
       <head>
          <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
       </head>

       <body>
          <h3> D3.js </h3>
          <script>
          var url = "http://192.168.50.198:5003/tracks"
             d3.json(url, function(data) {
                console.log(data);
             });
          </script>
       </body>
    </html>

If someone could tell me how to correct the python code to correct this situation.

reading I found that when installing an add-on "Allow-Control-Allow-Origin: *" in googlechrome and it works ... but it's not a solution for what I intend.

    
asked by Julian Andres Hernandez Villeg 31.08.2018 в 20:01
source

1 answer

0

I found a simple solution by using the instruction in the python code:  

response.headers.add ('Access-Control-Allow-Origin', '*')

  class Trask(Resource):
        def get(self):
            conn = db_connect.connect()
            query = conn.execute("SELECT BillingCity AS City ,SUM(Total) AS Total FROM invoices GROUP BY BillingCity;") 
            result =  [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]
            response = jsonify(result)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
    
answered by 05.09.2018 / 22:25
source