React+Flask 取数据报错

React+Flask Errors in fetching data

我正在关注 this tutorial 以使用 Flask 后端和 React 前端构建应用程序。当我 运行 应用程序时,它抛出如下所示的错误:

Errors I'm getting

我查看了其他堆栈溢出问题,但我看到的 none 似乎有效。这是一些代码。作为参考,您可以查看我发布的教程link。

我的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)
...

我的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)

...

我的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

这是一个 CORS 问题。您在 App.js

中获取数据的方式存在问题

尝试以下 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);