0

I'm have a little trouble with CORs in Python bottle. I am making a http request in AngularJS to my API to retrieve json data (which is implemented in Python bottle). I set it up many ways after googling around but I'm still getting the error in the chrome js console: XMLHttpRequest cannot load localhost:8080/ No 'Access-Control-Allow-Origin' header is present on the requested resource. Here is the code below:

app = Bottle()

class MetricsAPI():
    def __init__(self, host, port, timeout=5):
        self.db = redis.StrictRedis(host, port, db=0, socket_timeout=float(timeout))

    def day_metrics(self):
        metrics = self.db.hgetall('SampleMetrics')
        for key,value in metrics.iteritems():
            metrics[key] = json.loads(metrics[key])
        return metrics

@app.hook('after_request')
def enable_cors():
    """
    You need to add some headers to each request.
    Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'


@app.route('/metrics', method=['OPTIONS', 'GET'])
def metrics():
    db = MetricsAPI('localhost',6379);
    return db.day_metrics()


if __name__ == '__main__':
    run(app, host='localhost', port=8080)

My API works great but the problem is just CORs.

shapiro
  • 131
  • 10
  • response.headers['Access-Control-Allow-Origin'] = 'http: //localhost/' maybe using that will be a better configuration since I imagine your website is not mounted on the 8080 port since your bottle server is using that one – Aquiles Apr 08 '16 at 02:02
  • I'll try that out. Before I had '*' (which allow everything) and that did not work as well – shapiro Apr 08 '16 at 02:12
  • Still getting the error – shapiro Apr 08 '16 at 02:13
  • 3
    yes, if you had * and it didn't work that was not the problem... there is an answer to this on the forum: http://stackoverflow.com/q/17262170/2112269 – Aquiles Apr 08 '16 at 02:17
  • Shouldn't you be doing this instead? response.set_header('Access-Control-Allow-Origin', '*') response.add_header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS') – eatmeimadanish Mar 23 '18 at 14:40

0 Answers0