Tamjid
Tamjid

Reputation: 5506

Allow CORS to flask endpoint

I have developed a flask API and am attempting to send a POST request to it from a react app. However I keep receiving this error message:

Access to fetch at 'http://localhost:5000/api/project/' from origin 'http://localhost:3000' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource 
with CORS disabled.

Here is my fetch request in react:

fetch('http://localhost:5000/api/project/', {
      method: 'POST',
      mode: 'cors',
      body: JSON.stringify(project),
      credentials: 'include'
    }).then(function(response) {
      return response.json();
    }).then(function(data) {
      console.log(data)
    });

Here is my function for the endpoint:

    @cross_origin( supports_credentials = True )
    def get( self ):
        # Make sure user is logged in
        project_owner = session.get( 'username' )

        if project_owner is None:
            return response.cannot_process( ERROR_MSG.LOGIN_ERROR_MSG )

        # Establish db connection
        database_conn = db_mod.get_db()
        if database_conn is None :
            logging.error( ERROR_MSG.DB_ERROR_MSG )
            return response.service_unavailable( ERROR_MSG.DB_ERROR_MSG )

        # Try to get 'user' collection     
        user_collection = database_conn.get_collection( 'users' )
        if user_collection is None:
            logging.error( ERROR_MSG.COLLECTION_NOT_FOUND('users') )
            response.cannot_process( ERROR_MSG.COLLECTION_NOT_FOUND('users') )

        # Try to get 'projects' collection
        project_collection = database_conn.get_collection( 'projects' )
        if project_collection is None:
            logging.error( ERROR_MSG.COLLECTION_NOT_FOUND('projects') )
            response.cannot_process( ERROR_MSG.COLLECTION_NOT_FOUND('projects') )

        # Get owner document
        user_document = database_conn.get_document_by_key( user_collection, project_owner )
        documents = []
        # First find out all the owner projects
        owner_edge = database_conn.get_collection( 'project_ownership' )
        if owner_edge is not None:
            # Now get the owner project list
            owner_project_list = database_conn.get_edges_out( owner_edge, user_document )
            for owner_project in owner_project_list:
                owner_documents = database_conn.get_documents_by_template( project_collection, {"_id": owner_project.get("_to")} )
                if owner_documents is not None: documents.extend( owner_documents )

        # Next find out all the collaborator projects of this user
        collaboration_edge = database_conn.get_collection( 'project_collaboration' )
        if collaboration_edge is not None:
            # Now get the collaborator project list
            col_project_list = database_conn.get_edges_out( collaboration_edge, user_document )
            for col_project in col_project_list:
                col_documents = database_conn.get_documents_by_template( project_collection, {"_id": col_project.get("_to")} )
                if col_documents is not None: documents.extend(col_documents)

        project_data = []
        for document in documents:
            # Classification level is stored as a number, convert back to a string
            document['classification'] = fromClassificationLevel( document.get('classification') )
            project_data.append( marshal(document, project_data_model, skip_none = True ) )

        return response.ok_json( jsonify( {'result': project_data} ) )

I am unsure of how to set the access-control-allow-origin header from my API endpoint? I am currently using flask_cors module's @cross_origin() decorator for my endpoint. This works for my GET requests, but I am receiving this error for my POST request. Any idea how to solve this? Thanks

Upvotes: 0

Views: 13497

Answers (1)

MertG
MertG

Reputation: 763

If you haven't specific route for CORS, you may initialize all endpoints like

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

Flask-CORS

Upvotes: 4

Related Questions