Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access to fetch at 'http://127.0.0.1:5000/account/summary' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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. #333

Open
JacobDel opened this issue Jul 19, 2023 · 5 comments

Comments

@JacobDel
Copy link

Python: 3.9
Works sometimes with flask-cors 4.0.0
Works always with flask-cors 3.0.10

app = Flask(__name__)
CORS(app=app, resources={r"*": {"origins": "*"}})
logging.debug('CORS initialised')
@terrynguyen255
Copy link

terrynguyen255 commented Jul 20, 2023

I've encountered the same issue with flask-cors==3.0.10.

The issue appears once after a while then vanishes after minutes/hours, then appears again without no changes, no deployment at my server.

The issue cannot be bypassed by disabling security check in Chrome browser:

  • launching Chrome with security off: google-chrome --disable-web-security
  • installing Chome extension to skip CORS check: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

I will update this comment if I can figure it out.

@rajbirjohar
Copy link

rajbirjohar commented Dec 15, 2023

@terrynguyen255 did you ever figure this out?

Edit:
Decided this package was terrible and came up with my own solution.

def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = FRONTEND_URL  # Adjust as needed
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    return response
    
###

@app.after_request
def after_request(response):
    return add_cors_headers(response)

# Handles preflight requests
@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])
@app.route('/<path:path>', methods=['OPTIONS'])
def options_preflight(path):
    return add_cors_headers(make_response())

@Dev-hugo-hash
Copy link

@rajbirjohar Did it work?

@terrynguyen255 did you ever figure this out?

Edit: Decided this package was terrible and came up with my own solution.

def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = FRONTEND_URL  # Adjust as needed
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    return response
    
###

@app.after_request
def after_request(response):
    return add_cors_headers(response)

# Handles preflight requests
@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])
@app.route('/<path:path>', methods=['OPTIONS'])
def options_preflight(path):
    return add_cors_headers(make_response())

@rajbirjohar
Copy link

rajbirjohar commented Aug 22, 2024

@rajbirjohar Did it work?

@terrynguyen255 did you ever figure this out?

Edit: Decided this package was terrible and came up with my own solution.

def add_cors_headers(response):

response.headers['Access-Control-Allow-Origin'] = FRONTEND_URL  # Adjust as needed
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
return response

@app.after_request

def after_request(response):

return add_cors_headers(response)

Handles preflight requests

@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])

@app.route('/path:path', methods=['OPTIONS'])

def options_preflight(path):

return add_cors_headers(make_response())

@Dev-hugo-hash
Yes.

@Mohammad-Moiz
Copy link

Sending request to server with question: Tell me about problem statement of Nerdy Buddy
localhost/:1 Access to fetch at 'http://127.0.0.1:5000/ask' 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.
Main.js:79

   POST http://127.0.0.1:5000/ask net::ERR_FAILED 500 (INTERNAL SERVER ERROR)

handleAskQuestion @ Main.js:79
handleSubmit @ Main.js:129
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26179
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 15 more frames
Show less
Main.js:101 Error sending question: TypeError: Failed to fetch
at handleAskQuestion (Main.js:79:1)
at handleSubmit (Main.js:129:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
at dispatchEventsForPlugins (react-dom.development.js:9097:1)
at react-dom.development.js:9288:1
at batchedUpdates$1 (react-dom.development.js:26179:1)
at batchedUpdates (react-dom.development.js:3991:1)
at dispatchEventForPluginEventSystem (react-dom.development.js:9287:1)
at dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay (react-dom.development.js:6465:1)
at dispatchEvent (react-dom.development.js:6457:1)
at dispatchDiscreteEvent (react-dom.development.js:6430:1)
handleAskQuestion @ Main.js:101
await in handleAskQuestion
handleSubmit @ Main.js:129
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ re
act-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26179
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 15 more frames
Show less

this is my error on network tab of inspection method.what i can do to resolve it?

from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
from langchain.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA

OPENAI_API_KEY = 'sk-proj-jjpMBTWs2swbZTrZuNznT3BlbkFJKxRipsRgBZiNH1JhkVZh'
BOOK_PATH = '/home/srp/Downloads/WebGL/react-app/src/Backend/Data/NERDY BUDDY- WORKSHOP DOCUMENT V.1.1.pdf'

app = Flask(name)
CORS(app, resources={r"/ask": {"origins": "http://localhost:3000"}})

def create_chain():
"""
Creates a RetrievalQA chain for answer retrieval from a document.

Returns:
    RetrievalQA: The created RetrievalQA chain, or None if an error occurs.
"""
try:
    loader = PyPDFLoader(BOOK_PATH, extract_images=True)
    documents = loader.load()

    text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
    splits = text_splitter.split_documents(documents)

    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
                                       model_kwargs={'device': 'cpu'})
    vectorstore = FAISS.from_documents(documents=splits, embedding=embeddings)

    llm = ChatOpenAI(
        model="gpt-3.5-turbo",
        openai_api_key=OPENAI_API_KEY,
        temperature=0.7
    )

    custom_prompt_template = """Use the following pieces of information to answer the user's question.
      If you don't know the answer, just say that you don't know, don't try to make up an answer.

      Context: {context}
      Question: {question}

      Only return the helpful answer below and nothing else.
      Helpful answer:
      """

    prompt = PromptTemplate(template=custom_prompt_template,
                            input_variables=['context', 'question'])

    qa_chain = RetrievalQA.from_chain_type(
        llm, retriever=vectorstore.as_retriever(), chain_type_kwargs={"prompt": prompt}
    )

    return qa_chain

except FileNotFoundError as e:
    print(f"Error loading book: {e}")
    return None

Global variable to store the retrieval chain

chain = None

@app.route('/ask', methods=['POST'])
def ask_question():
"""
Handles the POST request to answer questions using the RetrievalQA chain.

Returns:
    JSON response with the answer or an error message.
"""
global chain

# Create the chain if it's not already created or if there was a previous error
if not chain:
    chain = create_chain()
    if not chain:
        return jsonify({'error': 'Error loading book'}), 500

query = request.json['query']
response = chain.invoke(query)
return jsonify({'response': response})

if name == 'main':
app.run(debug=True)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants