Issue with Axios POST request to Flask backend in AI model

I’m working on a React frontend and Flask backend, and I’m encountering a CORS issue when sending a POST request from the frontend to a Flask route (/predict). The GET request to the root (/) works fine, but the POST request fails with the following error: Error photo

I’ve already added CORS(app, resources={r"/*": {"origins": "*"}}) in the Flask backend, but it changes nothing.

Note: The AI model works fine with Google Colab.

react code:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function Home() {
    const [inputValue, setInputValue] = useState('');
    const [responseMessage, setResponseMessage] = useState('');
    const [message, setMessage] = useState('');
    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get('http://localhost:5000/');
                setMessage(response.data.message);
            } catch (error) {
                console.error("There was an error fetching the data!", error);
            }
        };

        fetchData();
    }, []);
    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            const response = await axios.post('http://localhost:5000/predict', { comment: inputValue }, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log('a');
            console.log(response);
            setResponseMessage(`Prediction: ${response.data.prediction}`);
        } catch (error) {
            console.error("There was an error sending the data!", error);
        }
    };

    return (
        <div className="App">
            <div className="form-container">
                {message && <h2>{message}</h2>}
                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        placeholder="Enter a comment"
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        required
                    />
                    <button type="submit">Analyze</button>
                </form>
                {responseMessage && <p className="response">{responseMessage}</p>}
            </div>
        </div>
    );
}

export default Home;

flask code:

import pandas as pd
from pandas import read_csv
import numpy as np
import sklearn
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/')
def home():
    return jsonify({"message": "Comment Spam Analysis"})

@app.route('/predict', methods=['POST'])
def predict():
    data=read_csv("./data/comments.csv")
    df = data[['CONTENT','CLASS']]
    df_x=df['CONTENT']
    df_y=df.CLASS
    corpus=df_x
    vectorizer=CountVectorizer()
    X=vectorizer.fit_transform(corpus)
    x_train,x_test,y_train,y_test=train_test_split(X,df_y,test_size=0.3,random_state=42)
    clf=MultinomialNB()
    clf.fit(x_train,y_train)
    clf.score(x_test,y_test)
    v=cross_val_score(clf,x_train,y_train,cv=10)
    v.mean()
    fit = clf.fit(x_train, y_train)
    predict = fit.predict(x_test)
    cmatrix = confusion_matrix(y_test, predict)
    print(cmatrix)
    from sklearn.metrics import classification_report
    print(classification_report(y_test,predict))
    import joblib as joblib
    joblib.dump(clf,'./model/comment_model.pkl')
    print("model dumped")
    clf=joblib.load('./model/comment_model.pkl')
    print("model loaded")
    
    if request.method=='POST':
        comment = request.form['comment']
        data = [comment]
        vect = vectorizer.transform(data).toarray()
        my_predection= clf.predict(vect)
    
    # return jsonify({"prediction": my_predection})
    return jsonify({"prediction": my_predection[0]})
    
if __name__ == '__main__':
    app.run(debug=True)

Can anyone help me figure out what I’m missing? Any advice on how to fix this CORS issue with the POST request or how I am using the AI model?