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.