问题描述
我在 React 应用程序上使用 get 请求来运行一个函数,该函数到目前为止只是在我的 Flask api 中“打印”出数据。我可以点击端点,并收到一个“响应”,但我不确定如何将 JSON 数据附加到 FLASK 给出的响应中。
PS:是否需要将此 JSON 数据发布到数据库,然后从我的 create react 应用程序中检索它?或者我可以做我正在尝试做的事情,即简单地运行 GET 请求,让它生成 JSON,然后在 GET 响应中将其发送回 Create React App。
Flask API (views.py)
@main.route('/add_post')
def add_post():
temparray = []
*code that pushes json object into temparray [{},{},{}]*
time.sleep(5)
post_data = temparray
print (post_data)
^^^^^^How do I attach post_data to the response?^^^^^^^^^
return 'Done',201
创建 React 应用程序 (app.js)
import { useEffect } from 'react';
import './App.css';
function App() {
useEffect(() => {
fetch("/add_post").then(response =>
console.log(response)
)
},[])
return (
<div className="App">
<h1>
test
</h1>
</div>
);
}
解决方法
在这里,
fetch("/add_post").then(response =>
console.log(response)
)
改为这样做
fetch("/add_post")
.then(response => response.json())
.then(jsonData => {
// do something with the data,e.g. setState
})
,
您可以从 return post_data
函数中简单地 add_post
。这将自动将有效的 dict 转换为 JSON(即 jsonify
)