COR Error with React and Flask

I there, I am trying to create a simple app where use enters a question and gets a response.

Front End - React Native
BE - Simple Flask Service which calls OpenAI APIs

Challenge - I keep getting the CORS error despite trying various fixes.

Here is ReactNative frontend:

// LandingPage.tsx
import axios from 'axios';
import React, {useState} from 'react';
import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native';

const LandingPage: React.FC = () => {
  const [question, setQuestion] = useState('');
  const [loading, setLoading] = useState(false);

  // Function to handle the submission of the question
  const handleSubmit = async () => {
    // Implement the logic to handle the question submission
    if (!question.trim()) {
      Alert.alert('Please enter a question');
      return;
    }

    try {
      setLoading(true);
      const response = await axios.post(
        'http://localhost:5000/ask',
        {question},
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      setLoading(false);
      Alert.alert('Response', JSON.stringify(response.data));
      setQuestion(''); // Reset the question input
    } catch (error) {
      setLoading(false);
      if (axios.isAxiosError(error)) {
        console.error('Error:', error.response?.data || error.message);
        Alert.alert(
          'Error',
          error.response?.data?.message ||
            'There was an error processing your request',
        );
      } else {
        console.error('Error:', error);
        Alert.alert('Error', 'There was an error processing your request');
      }
    }
  };

Here is Flask BE:

from flask import Flask, request, jsonify
from flask_cors import CORS
import openai

openai.api_key = 'mykey'

app = Flask(__name__)

# Set CORS options globally for all routes and origins
#CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}}, headers=['Content-Type', 'Authorization'])
CORS(app)

@app.route('/ask', methods=['POST'])
def ask():
    question = request.json.get('question')
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=question,
        temperature=0.5,
        max_tokens=100
    )
    return jsonify(response.choices[0].text.strip())

if __name__ == '__main__':
    app.run(debug=True,port=5000)

Here is Error in the Chrome Network Section:

Access to XMLHttpRequest at 'http://localhost:5000/ask' from origin 'http://localhost:9090' 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.

you need put a header about cors in this

// LandingPage.tsx
import axios from 'axios';
import React, {useState} from 'react';
import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native';

const LandingPage: React.FC = () => {
  const [question, setQuestion] = useState('');
  const [loading, setLoading] = useState(false);

  // Function to handle the submission of the question
  const handleSubmit = async () => {
    // Implement the logic to handle the question submission
    if (!question.trim()) {
      Alert.alert('Please enter a question');
      return;
    }

    try {
      setLoading(true);
      const response = await axios.post(
        'http://localhost:5000/ask',
        {question},
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      setLoading(false);
      Alert.alert('Response', JSON.stringify(response.data));
      setQuestion(''); // Reset the question input
    } catch (error) {
      setLoading(false);
      if (axios.isAxiosError(error)) {
        console.error('Error:', error.response?.data || error.message);
        Alert.alert(
          'Error',
          error.response?.data?.message ||
            'There was an error processing your request',
        );
      } else {
        console.error('Error:', error);
        Alert.alert('Error', 'There was an error processing your request');
      }
    }
  };
          headers: {
            'Content-Type': 'application/json',
          },

Can you please elaborate? I already have the application/json. What else should be added?

@sokland the issue its in Flask BE Python

Flask BE Python try replace this

# Set CORS options globally for all routes and origins
#CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}}, headers=['Content-Type', 'Authorization'])
CORS(app)

by

# Set CORS options for /ask route to allow requests from the specific origin
CORS(app, resources={r"/ask": {"origins": "http://localhost:9090"}})

Thank for for response @b0zal !

I updated the BE with the suggestion. Also I tried another variant suggested by ChatGPT but still doesn’t work when I try to call the BE from React FE.

CORS(app, resources={r"ask": {"origins": "http://localhost:9090"}},supports_credentials=True, headers=['Content-Type', 'Authorization'])

But surprisingly, when I try to test the BE using terminal it works fine.

 curl -X POST -H "Content-Type: application/json" -d '{"question":"What is the capital of Peru??"}' http://localhost:5000/ask
"The capital of Peru is Lima."

Also, I tried to update the FE as well by adding the origin header.

  }

    try {
      setLoading(true);
      const response = await axios.post(
        'http://localhost:5000/ask',
        {question},
        {
          headers: {
            'Content-Type': 'application/json',
            Origin: 'http://localhost:9090', // Set the origin header
          },
        },
      );```


I tried to ask Bard and ChatGPT and I tried all their suggestions as well but still getting the same error. 

I use MacBook Pro M2 and running latest Apple OS. 

anything else I can try. Appreciate your help.

Hey. did you solve this? i am having the same issue and i am stuck