skip to Main Content

I am not sure why I am getting a CORS error when I try to extract the body from a http request from the react app.
I dont get the error when I use postman to make the http error to the python server.

this is the python app.py file. I have labeled the line that is giving me an error when its not commented out.

I could not find any other stackoverflow issue like this.
there was a simimlar-ish question but it didnt help (CORS error while making REST API calls from React JS application)
chatgpt was not helping either

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

from routes.question_data_routes import question_data_bp
from routes.user_routes import user_bp
from middleware.auth import check_authorization
from services.mongodb import MongoDBConnector
from dotenv import load_dotenv

app = Flask(__name__)
load_dotenv()

CORS(app, origins=["http://localhost:3000"], methods=["GET", "POST"], allow_headers=["Content-Type"])

mongo_connector = MongoDBConnector(app)

@app.route('/api/user/signup', methods=['POST', 'OPTIONS'])  # Make sure OPTIONS method is handled
def signup():
    # Your signup logic
    data = request.get_json()  # THIS IS CAUSING THE ISSUE IF I DONT COMMENT IT OUT

    return jsonify({'message': 'Signup successful'}), 200

here is the error that I am getting::

auth:1 Access to fetch at 'http://127.0.0.1:5000/api/user/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
auth.js:9     POST http://127.0.0.1:5000/api/user/signup net::ERR_FAILED
singUp @ auth.js:9
handleSubmit @ RegisterForm.js:13
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:26140
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
auth.js:20 Error during signup: TypeError: Failed to fetch
    at UserBackEndAPI.singUp (auth.js:9:1)
    at handleSubmit (RegisterForm.js:13: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)
overrideMethod @ console.js:213
singUp @ auth.js:20
await in singUp (async)
handleSubmit @ RegisterForm.js:13
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:26140
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 1 more frame
auth.js:9        Uncaught (in promise) TypeError: Failed to fetch
    at UserBackEndAPI.singUp (auth.js:9:1)
    at handleSubmit (RegisterForm.js:13: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)

not sure why I dont get the error if I comment out "data = request.get_json()"

here is the code from the react app that makes the api call::


  async singUp(name, email, password) {
    try {
      const response = await fetch(`${this.baseUrl}/api/user/signup`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, email, password }),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Error during signup:', error);
      throw error;
    }
  }

it works perfect if I make the post request from postman

why am i getting that weird error when i try to extract the data from the body??

postman1

postman2

2

Answers


  1. Chosen as BEST ANSWER

    this ended up doing the trick::

    def signup_controller():
        print('signup_controller()')
        if request.method == 'OPTIONS':
            print('request.method == OPTIONS')
            # Handle CORS preflight request
            response = jsonify({'message': 'CORS preflight successful'})
            response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            return response, 200
        print('AFTER CORS')
    

    so just put that at the front. not sure why it works but it works nice.


  2. If you run the code only in your machine then you can use the following extension which can prevent the CORS error

    CORS Access Control.

    This can help to test your react app during development.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search