How to Solve CORS for python-eve[ ]
Recently, I am building a rest api for
python-eve. Everything works like charm, except my browser is complaining
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
Some googling indicates it is a problem of Cross-Origin Resource Sharing (CORS), where python-eve, by default, doesn’t support
PUT method cross origin. To do that, I found a solution from stackoverflow, where I made a small modification:
@app.after_request def after_request(response): response.headers.set('Access-Control-Allow-Origin', '*') response.headers.set('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response
Note, I use set instead of add there, as I found when I use
add, I get response with two
Access-Control-Allow-Methods, where one is empty the other one has value as I specify here.
Now my response head is like
Access-Control-Allow-Headers:Content-Type,Authorization,If-Match Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS Access-Control-Allow-Origin:* Access-Control-Expose-Headers: Access-Control-Max-Age:21600 Content-Length:179 Content-Type:application/json Date:Wed, 06 Sep 2017 02:36:56 GMT Server:Eve/0.7.4 Werkzeug/0.11.15 Python/3.5.2 Vary:Origin
Access-Control-Allow-Headers: Access-Control-Allow-Methods: Access-Control-Allow-Origin: Access-Control-Expose-Headers: Access-Control-Max-Age:21600 Content-Length:0 Content-Type:text/html; charset=utf-8 Date:Wed, 06 Sep 2017 02:35:41 GMT Server:Eve/0.7.4 Werkzeug/0.11.15 Python/3.5.2 Vary:Origin
Written on September 5, 2017