Getting CORS Error When Making POST Request from Localhost Frontend to Localhost Backend in Flask

59 Views Asked by At

I am trying to learn how to use Flask and related technologies, but I don't know why I keep encountering this CORS error. I've tried everything I could find online, but nothing seems to work. The GET route is functioning normally, but the POST request is resulting in a CORS error.

My code:

import os
from flask import Flask
from flask_cors import CORS

from app.extensions import db, migrate, api

from app.controller.livro_controller import api as livro_ns

class testConfig():
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'flask_boilerplate_main.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    
def create_app():
    app = Flask(__name__)
    app.config.from_object(testConfig)
    CORS(app)
    db.init_app(app)
    migrate.init_app(app, db)
    api.init_app(app)
    
    api.add_namespace(livro_ns, path="/livro")

    return app

livro_controller.py

from flask import request, make_response
from flask_restx import Resource, marshal
from flask_cors import CORS, cross_origin

from app.util.dto import LivroDto
from app.service.livro_service import (
    editar_livro,
    excluir_livro,
    listar_todas_livros,
    criar_livro,
)

api = LivroDto.api
_livro = LivroDto.livro


@api.route("/")
class Livro(Resource):
    @api.doc('list_of_registered_users')
    @api.response(201, 'User successfully created.')
    @api.expect(_livro, validate=True)
    def post(self):
        data = request.json
        try:
            response = criar_livro(data)
            return response, 201
        except Exception as e:
            return {"message": str(e)}, 500

    @api.marshal_list_with(_livro, envelope="data")
    def get(self):
        try:
            return listar_todas_livros(), 200
        except Exception as e:
            return {"message": str(e)}, 500


@api.route("/<int:id_livro>")
@api.param("id_livro", "Book ID")
class LivroComId(Resource):
    @api.expect(_livro, validate=True)
    def put(self, id_livro):
        data = request.json
        try:
            response = editar_livro(id_livro, data)
            return response, 200
        except Exception as e:
            return {"message": "An error occurred while updating the book."}, 500

    def delete(self, id_livro):
        try:
            response = excluir_livro(id_livro)
            return response, 204
        except Exception as e:
            return {"message": "An error occurred while deleting the book."}, 500

Front request:

import axios from "axios";
import { livroType } from "../types/livro";


export function criarLivro(livro: livroType) {
    return axios.post("http://localhost:5000/livro", livro);
}

export function todosLivros() {
    return axios.get("http://localhost:5000/livro"); 
}

ERROR:

Access to XMLHttpRequest at 'http://localhost:5000/livro' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

POST http://localhost:5000/livro net::ERR_FAILED

xhr.js:158 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

apiFunctions.ts:6 XHR failed loading: POST "http://localhost:5000/livro".

0

There are 0 best solutions below