Home > Software design >  React Flask Errors in fetching data
React Flask Errors in fetching data

Time:04-26

I am following this tutorial to build an app with Flask backend and React Frontend. When I run the app, it throws the errors shown below:

  • Preflight response not successful
  • Fetch API cannot load https://localhost/articles due to control checks

Errors I'm getting

I looked through other stack overflow questions but none that I saw seemed to work. Here is some of the code. For reference, you could see the tutorial link I posted.

My routes.py:

...
app = create_app()

@app.route("/articles/", methods=["GET"], strict_slashes=False)
def articles():

    articles = Articles.query.all()
    results = articles_schema.dump(articles)

    return jsonify(results)
...

My app.py:

...
db = SQLAlchemy()
migrate = Migrate()
ma = Marshmallow()
cors = CORS()


def create_app():
    """Application-factory pattern"""
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)
    cors.init_app(app)

...

My App.js:

function App() {
    const [articles, setArticles] = useState([])

    // Modify the current state by setting the new data to
    // the response from the backend
    useEffect(() => {
        fetch("http://localhost:5000/articles", {
            methods: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        })
            .then((response) => response.json())
            .then((response) => setArticles(response))
            .catch((error) => console.log(error))
    }, [])

    return (
        <div className="App container m-4">
            <div className="row">
                <div className="text-center">
                    <h1>Connecting a React Frontend to a Flask Backend.</h1>
                </div>
            </div>

            <ArticleList articles={articles} />
        </div>

ArticleList.js

const ArticleList = (props) => {
    return (
        <div className="m-2">
            {/* Display the article details if article is not None */}
            {props.articles &&
                props.articles.map((article) => {
                    return (
                        <div key={article.id}>
                            <h2 className="text-primary"> {article.title} </h2>
                            <p> {article.body} </p>
                            <p> {article.date} </p>
                            <hr />
                        </div>
                    )
                })}
        </div>
    )
}

export default ArticleList

CodePudding user response:

This is a CORS issue. It is a problem with the way you're fetching data in App.js

Try the following headers -

  const headers = new Headers();
  headers.set('Accept', 'application/json');
  headers.set('Access-Control-Allow-Credentials', 'true');
  headers.set('Access-Control-Allow-Origin', 'true');
  headers.set('Content-Type', 'application/json');

    const response = await fetch(url, {'GET', headers})
      .then(r => r.json()).catch(onError);  
  • Related