如何在 React 应用程序中使用 Fetch 向 Flask API 发送 POST 请求
How to send a POST request to Flask API using Fetch in a React app
为了说明我的问题,我做了一个简单的例子
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
fetch('/get')
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
useEffect(() => {
fetch('/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request' })
})
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request' })
})
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
return <div className="App"></div>;
}
export default App;
在第一个 useEffect
挂钩中,我向我的烧瓶 API 发送一个 GET
请求并记录请求的响应。
在第二个 useEffect
挂钩中,我正在向我的烧瓶 API 发送一个 POST
请求并记录请求的响应。
在第三个useEffect
挂钩中,我正在向jsonplaceholder.typicode.com/posts 发送一个POST
请求并记录请求的响应。
第一个useEffect
输出:
第二个useEffect
输出:
第三个useEffect
输出:
我使用相同的 post 请求代码来请求我的 Flask API 和 jsonplaceholder.typicode.com API 但是我的 API 的响应总是空的对象 {}
。这不是预期的。它应该 return 这个 { title: 'React POST Request' }
对象。我试图找到解决方案,但对我没有任何帮助。
我的简单 Flask API:
import time
from flask import Flask, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/get', methods=['GET'])
def get():
return { "title": 'React GET Request' }
@app.route('/post', methods=['POST'])
def post():
return request.args
.flaskenv file
:
FLASK_APP=api.py
FLASK_ENV=development
package.json
文件:
{
"name": "flask-app-demo",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.8",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
顺便说一下,我正在使用 create-react-app
包来设置我的 React 应用程序。
没错。那是因为 request.args
就是这样。
https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20args#flask.Request.args
The parsed URL parameters (the part in the URL after the question mark).
request.args
是查询字符串参数,您在 POST
.
中没有提供任何查询字符串参数
我对烧瓶生锈了,但文档说 request.json
会 return 你的 json 编码 post.
https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20json#flask.Request.json
为了说明我的问题,我做了一个简单的例子
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
fetch('/get')
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
useEffect(() => {
fetch('/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request' })
})
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request' })
})
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
return <div className="App"></div>;
}
export default App;
在第一个 useEffect
挂钩中,我向我的烧瓶 API 发送一个 GET
请求并记录请求的响应。
在第二个 useEffect
挂钩中,我正在向我的烧瓶 API 发送一个 POST
请求并记录请求的响应。
在第三个useEffect
挂钩中,我正在向jsonplaceholder.typicode.com/posts 发送一个POST
请求并记录请求的响应。
第一个useEffect
输出:
第二个useEffect
输出:
第三个useEffect
输出:
我使用相同的 post 请求代码来请求我的 Flask API 和 jsonplaceholder.typicode.com API 但是我的 API 的响应总是空的对象 {}
。这不是预期的。它应该 return 这个 { title: 'React POST Request' }
对象。我试图找到解决方案,但对我没有任何帮助。
我的简单 Flask API:
import time
from flask import Flask, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/get', methods=['GET'])
def get():
return { "title": 'React GET Request' }
@app.route('/post', methods=['POST'])
def post():
return request.args
.flaskenv file
:
FLASK_APP=api.py
FLASK_ENV=development
package.json
文件:
{
"name": "flask-app-demo",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.8",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
顺便说一下,我正在使用 create-react-app
包来设置我的 React 应用程序。
没错。那是因为 request.args
就是这样。
https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20args#flask.Request.args
The parsed URL parameters (the part in the URL after the question mark).
request.args
是查询字符串参数,您在 POST
.
我对烧瓶生锈了,但文档说 request.json
会 return 你的 json 编码 post.
https://flask.palletsprojects.com/en/1.1.x/api/?highlight=request%20json#flask.Request.json