skip to Main Content

I’m trying to pull of a fetch request from my front-end (ReactJS Project) to my flask api endpoint. But whenever I try to do so, this weird error comes up

Access to fetch at 'https://2483-103-79-250-41.ngrok-free.app/check' (redirected from 'http://2483-103-79-250-41.ngrok-free.app/check') 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.

I have my origin specified in the api as well (Current origin -> http://localhost:3000)
Below is my flask api code

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

app = Flask(__name__)
CORS(app, origins="http://localhost:3000")

@app.route("/create_user", methods=["POST"])
def sign_up():
    body = request.get_json()
    res = utils.sign_up_user(
        user_name=body['user_name'],
        user_password= body['user_password'],
        user_email= body['user_email']
    )
    return res

@app.route("/login_user", methods=["POST"])
def log_in():
    body = request.get_json()
    res = utils.log_in_user(
        user_name=body['user_name'],
        user_password=body['user_password'],
        user_email=body['user_email']
    )
    return res

@app.route("/check", methods=["GET"])
def check():
    return {
        "status":"ok"
    }

if __name__=="__main__":
    app.run(debug=True)

and below is the function where I try to do the fetch request

const checkApi = async (fetchUri) => {
        try {
            let uri = `${fetchUri}/check`
            const rawRes = await fetch(uri)
            const res = await rawRes.json()
            if (res.status == "ok") {
                localStorage.setItem("@uri", String(fetchUri))
                setUri(fetchUri)
                if(user.exists){
                    navigate("/app")
                }else{
                    navigate("/login")
                }
                return
            }
            clearBadUri()
        } catch (error) {
            clearBadUri()
        }
    }

I tried to use the function to do a fetch request to check if the api is working. But no matter what type of request I do, it gives me the CORS error, I even set the CORS origin as my current react origin.
I would like to know how to avoid this error and what it means.

3

Answers


  1. Chosen as BEST ANSWER

    My setup -> I had a react js project as my frontend being hosted on my pc. Then I had a flask server running on my pc but being port forwarded using ngrok, and I was trying to use the uri ngrok gave me in react js project to access my flask server.

    My problem -> An error occurred named "CORS not allowing requests" and it was because the server wasn't configured properly to allow CORS i suppose? I'm not a master at this but after a lot of headache chat GPT got me an answer that worked for me.

    from flask import Flask, request
    import utils
    from flask_cors import CORS, cross_origin
    
    app = Flask(__name__)
    cors = CORS(app, resources={r"/*": {"origins": "http://localhost:3000"}}) #Add your url of project here
    
    @app.route("/create_user", methods=["POST"])
    @cross_origin() #add this before every endpoint
    def sign_up():
        body = request.get_json()
        res = utils.sign_up_user(
            user_name=body['user_name'],
            user_password= body['user_password'],
            user_email= body['user_email']
        )
        return res
    
    @app.route("/login_user", methods=["POST"])
    @cross_origin()
    def log_in():
        body = request.get_json()
        res = utils.log_in_user(
            user_name=body['user_name'],
            user_password=body['user_password'],
            user_email=body['user_email']
        )
        return res
    
    @app.route("/check", methods=["GET"])
    @cross_origin()
    def check():
        return {
            "status":"ok"
        }
    
    if __name__=="__main__":
        app.run(debug=True)
    

    This worked for me, hope it helps someone else as well.


  2. What is the URL in the browser? In case that is https://2483-103-79-250-41.ngrok-free.app:

    Instead of CORS(app, origins="http://localhost:3000") you have to put

    CORS(app, origins="https://2483-103-79-250-41.ngrok-free.app")
    
    Login or Signup to reply.
  3. To solve this error, you need to allow cross-origin requests on your server. In your Flask code, you are already using the Flask-CORS extension to allow requests from "http://localhost:3000". However, you might need to specify the HTTP methods allowed for CORS requests.
    modify

    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app, origins="http://localhost:3000", supports_credentials=True, methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
    

    The supports_credentials=True argument is used to allow cookies to be sent with cross-origin requests.

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