#๐Ÿ”’ Flask API blocked by CORS policy

50 messages ยท Page 1 of 1 (latest)

dreamy dove
#

I am using flask for a simple api which logins registers and update some data(notes) I am also using JWT for keeping track of logined users and the data is sent in json format

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

app = Flask(__name__)
cors = CORS(
    app,
    supports_credentials=True,
)

@app.after_request
def after_request(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
   
    return response

@app.route("/register", methods=["POST"])
@cross_origin()
def register():

    name = request.get_json()["name"]
    password = request.get_json()["password"]

    existing_user = mycol.find_one({"name": name})
    if existing_user:
        print("User already exists. Please login.")
        return jsonify({"message": "User already exists. Please login."}), 400

    hashed_password = generate_password_hash(password)
    user_id = str(uuid.uuid4())
    new_user = {
        "name": name,
        "password": hashed_password,
        "user_id": user_id,
        "notes": [],
    }
    mycol.insert_one(new_user)
    return jsonify({"message": "User registered successfully."}), 201

I feel this is the relevant part of my code. I am using this api in a react js website that throws error

Access to fetch at 'http://127.0.0.1:5000/' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:5173, POST', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
storm vectorBOT
#

@dreamy dove

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

latent thicket
#

From the error, it seems like you're supplying multiple Access-Control-Allow-Origin headers

#

(why do you have both cors = CORS(...) and an app.after_request function?)

dreamy dove
#
HTTP/1.1 404 NOT FOUND
Server: Werkzeug/3.1.3 Python/3.12.9
Date: Thu, 08 May 2025 11:40:51 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 207
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Vary: Origin
Access-Control-Allow-Origin: *
Connection: close
latent thicket
#

Sounds like flask_cors is adding the first Access-Control-Allow-Origin header and your middleware is adding the second one. You have to choose which one to keep

#

the allowed origins are probably configurable in flask_cors, you'll need to check the documentation

dreamy dove
#

like there 2 request in the debug toots fist one has no responce headers second one has the above

dreamy dove
latent thicket
dreamy dove
#

if i remove after request getting

#

Request URL:
http://127.0.0.1:5000/
Referrer Policy:
strict-origin-when-cross-origin
content-type:
application/json
referer:
http://localhost:5173/
sec-ch-ua:
"Brave";v="135", "Not-A.Brand";v="8", "Chromium";v="135"
sec-ch-ua-mobile:
?0
sec-ch-ua-platform:
"Linux"
user-agent:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36

latent thicket
#

That's the request headers

#

show the full screenshot

dreamy dove
#

i just seleced the recent request

latent thicket
#

What's the response?

#

Why is the request red?

#

What do you see in Console?

dreamy dove
#

idk ig it failed or some thing let me see

#

Pinged your deployment. You successfully connected to MongoDB!
[]

  • Debugger is active!
  • Debugger PIN: 573-281-245
    127.0.0.1 - - [08/May/2025 17:20:21] "OPTIONS / HTTP/1.1" 404 -
    127.0.0.1 - - [08/May/2025 17:20:41] "OPTIONS / HTTP/1.1" 404 -
    127.0.0.1 - - [08/May/2025 17:21:26] "OPTIONS / HTTP/1.1" 404 -
    127.0.0.1 - - [08/May/2025 17:21:37] "OPTIONS / HTTP/1.1" 404 -
latent thicket
#

I meant the Console tab in the browser

dreamy dove
#

modified this too

app = Flask(__name__)
cors = CORS(
    app,
    supports_credentials=True,
    origin="*",
)
latent thicket
#

It's supposed to be origins from the docs, seems like a bug that it doesn't raise an error

latent thicket
# dreamy dove

Can you show how you're making the request from JavaScript?

#

Seems like you're making a request to / instead of /register

dreamy dove
#

const register = async (name, password) => {
  const response = await fetch("http://127.0.0.1:5000", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ name, password }),
  });

  const data = await response.json();
  console.log(data);

  return [{ ...data }, response.ok];
};
latent thicket
#

right, you're making a request to http://127.0.0.1:5000, not http://127.0.0.1:5000/register

dreamy dove
#

oh wait

latent thicket
#

which is why you're getting a 404 response

dreamy dove
#

oh

#

i fixed that now but even other endpoints were not woking and now i get a 500 error ig i deleted the register from uri by mistake

latent thicket
#

A 500 error means you're getting some exception on the backend, you'll need to check the logs

#

Do you need CORS for something in the application, or do you just need it for development when you have the backend and the frontend on different origins? In the latter case, maybe you should drop the dependency on flask-cors and just have a simple middleware that you only enable for development

dreamy dove
#

but thats some error in code ig let me check

dreamy dove
#
from flask import Flask, request, jsonify
import jwt
import uuid
from dotenv import load_dotenv
import os
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

load_dotenv()
jwt_secret = os.getenv(
    "jwt_secret",
)
db_password = os.getenv(
    "db_password",
)
db_user = os.getenv(
    "db_user",
)

uri = f"mongodb+srv://{db_user}:{db_password}@cluster0.3rlu3lj.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"


# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi("1"))

try:
    client.admin.command("ping")
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

mydb = client["Notes"]
mycol = mydb["Users"]
print(list(mycol.find({})))


def check_token(token):
    try:
        decoded = jwt.decode(token, jwt_secret, algorithms=["HS256"])
        print(decoded)
        return decoded
    except jwt.ExpiredSignatureError:
        return False
    except jwt.InvalidTokenError:
        return False


app = Flask(__name__)
# cors = CORS(
#     app,
#     supports_credentials=True,
#     origins="*",
# )


@app.after_request
def after_request(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
   
    return response


@app.route("/register", methods=["POST", "OPTIONS"])
# @cross_origin()
def register():

    name = request.get_json()["name"]
    password = request.get_json()["password"]

    existing_user = mycol.find_one({"name": name})
    if existing_user:
        print("User already exists. Please login.")
        return jsonify({"message": "User already exists. Please login."}), 400

    hashed_password = generate_password_hash(password)
    user_id = str(uuid.uuid4())
    new_user = {
        "name": name,
        "password": hashed_password,
        "user_id": user_id,
        "notes": [],
    }
    mycol.insert_one(new_user)
    return jsonify({"message": "User registered successfully."}), 201
#

this is part of the modified code

#

127.0.0.1 - - [08/May/2025 17:40:22] "OPTIONS /register HTTP/1.1" 415 - in flask app shell

#

this is the log i am getting from console

wise axle
#

Are you still getting errors?

dreamy dove
#

no more

#

it works now i am using flask_cors

storm vectorBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.