Skip to content Skip to sidebar Skip to footer

Getting Cors (cross-origin...) Error When Using Python Flask-restful With Consuming Angularjs (using $http)

I use a python program for providing a restful service with the flask-restful extension. I want to consume it with a AngularJS app. Everything works (for the moment) on my localhos

Solution 1:

You can solve this using the after_request hook:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

You can see a demo on how to use it here - http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/

The tutorial also uses Flask-restful.

Solution 2:

If you do an AngularJS POST call using CORS sometimes it triggers (depending on your MIME/Content-Type) a prior OPTIONS call to check that the cross-server request is valid before sending all the POST data. Since your API does not have an options method, Flask takes the call instead of Flask-Restful, and it does not set up the CORS options which are only defined for the API resource.

You may solve the problem defining a dummy options handler:

defoptions(self):
    pass

To make the whole thing work, define the cors options using

api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])] 

I don't know why, but I had to explicitly add all the headers to the list; using headers = '*' did not work for me. You might also have to add the decorators before hooking up the resources to the API.

Solution 3:

As posted on another thread, here is my solution:

To allow remote CORS requests on your web service api, you can simply initialize your flask restful API like this:

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"*": {"origins": "*"}})
api = Api(app)

This adds the CORS header to your api instance and allows a CORS request on every path from every origin.

Solution 4:

The Flask extension Flask-cors (https://github.com/corydolphin/flask-cors) worked well for me.

Post a Comment for "Getting Cors (cross-origin...) Error When Using Python Flask-restful With Consuming Angularjs (using $http)"