Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-RESTplus CORS request not adding headers into the response

Tags:

python

rest

flask

I have an issue trying to setup CORS for my REST API. I'm currently using the Flask-Restplus package. Here's what my endpoints look like :

@api_ns.route('/some/endpoint')
@api_ns.response(code=400, description='Bad Request.')
class AEndpointResource(Resource):

    @api_ns.param(**api_req_fields.POST_DOC)
    @api_ns.expect(POST_REQUIRED_BODY)
    @api_ns.marshal_with(code=201,
                     fields=my_api_models.MyEndpointResponse.get_serializer(),
                     description=my_api_models.MyEndpointResponse.description)
    def post(self) -> Tuple[my_api_models.MyEndpointResponse, int]:
        """
        The post body
        """
        # Some logic here
        return response, 200

If I code a small javascript snippet and I try to launch it in a browser, I will get an error because there's no CORS headers. I'm seeing the Flask-Restplus is already handling the OPTIONS request without me telling him anything. (This makes sense according to this link, mentioning that since Flask 0.6, the OPTIONS requests are handled automatically)

My problem is that even when I try to decorate my endpoint using :

from flask-restplus import cors   # <--- Adding this import

...
class AnEndpointResource(Resource):
    ...
    @my_other_decorators
    ...
    @cors.crossdomain(origin='*')  # <--- Adding this new decorator on my endpoint
    def post(self) -> Tuple[my_api_models.MyEndpointResponse, int]:
        ...

Nothing changes and I still get the same result as before. I get an HTTP 200 from the OPTIONS request automatically handled as before, but I don't see my new headers (i.e. Access-Control-Allow-Origin) in the response.

Am I missing something ?

like image 555
ElCapitaine Avatar asked Jun 05 '18 20:06

ElCapitaine


2 Answers

Using Flask-CORS, it works:

from flask import Flask, request
from flask_restplus import Resource, Api, fields
from flask_cors import CORS

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
api = Api(app)
app.config.from_object(__name__)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})
like image 144
Gianfranco P. Avatar answered Nov 13 '22 07:11

Gianfranco P.


When doing local testing on my laptop and in my browser, I was able to solve the cors problem by adding the header in the response.

before: return state, 200

after: return state, 200, {'Access-Control-Allow-Origin': '*'}

like image 3
user985366 Avatar answered Nov 13 '22 08:11

user985366