Post 从 React 到 Flask 的请求
Post request from react to flask
我正在尝试使用以下代码向 Flask 发送一个 post 请求:
function App() {
const [currentTime, setCurrentTime] = useState(0);
const [accessToken, setAccessToken] = useState(null);
const clicked = 'clicked';
useEffect(() => {
fetch('/time').then(res => res.json()).then(data => {
setCurrentTime(data.time);
});
}, []);
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example',action: 'clicked' })
};
var myParams = {
data: requestOptions
}
fetch('http://127.0.0.1:5000/login', myParams)
.then(response => response.json())
.then(data => setAccessToken(data.access_token));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);
return (
<div className="App">
<div className="leftPane">
<div className="joyStick" >
<Joystick size={300} baseColor="gray" stickColor="black" ></Joystick>
</div>
<p>The current time is {currentTime}.</p>
<p>The access token is {accessToken}.</p>
</div>
烧瓶代码是
from __future__ import print_function
from flask import Flask, jsonify, request
from flask_cors import CORS
import time
from flask import Flask
import sys
robotIP="10.7.4.109"
PORT=9559
app = Flask(__name__)
access_token='a'
action="d"
@app.route('/time')
def get_current_time():
return {'time': time.time()}
@app.route('/login', methods=['POST'])
def nao():
nao_json = request.get_json()
if not nao_json:
return jsonify({'msg': 'Missing JSON'}), 400
action = nao_json.get('action')
access_token= action+'s'
print(access_token, file=sys.stderr)
return jsonify({'access_token': access_token}), 200
但是每次我 运行 他们两个,我都会收到 'msg': 'Missing JSON' 我已经定义的消息并且来自反应的数据在烧瓶中永远不可用,即使获取请求 works.I 我不确定我在这里做错了什么。
问题实际上是这是一个跨源请求,必须得到服务器的允许。
将此功能放在您的 Python 代码中:
@app.after_request
def set_headers(response):
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Allow-Methods"] = "*"
return response
注:
如果从同一台服务器提供 React,则没有必要。
您应该将这些 headers 的值设置为在生产中尽可能严格。上面的例子太宽容了。
您可以从 Flask 为您的 React 应用程序提供服务,因此不需要设置这些 headers。您可以使用类似这样的东西来提供主反应文件:
@app.route('/', defaults={'path': ''})
@app.route('/<string:path>')
@app.route('/<path:path>')
def index(path: str):
current_app.logger.debug(path)
return bp_main.send_static_file('path/to/dist/index.html')
其中 path/to/dist/index.html
将位于静态文件夹中。
查看更多信息:
我正在尝试使用以下代码向 Flask 发送一个 post 请求:
function App() {
const [currentTime, setCurrentTime] = useState(0);
const [accessToken, setAccessToken] = useState(null);
const clicked = 'clicked';
useEffect(() => {
fetch('/time').then(res => res.json()).then(data => {
setCurrentTime(data.time);
});
}, []);
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example',action: 'clicked' })
};
var myParams = {
data: requestOptions
}
fetch('http://127.0.0.1:5000/login', myParams)
.then(response => response.json())
.then(data => setAccessToken(data.access_token));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);
return (
<div className="App">
<div className="leftPane">
<div className="joyStick" >
<Joystick size={300} baseColor="gray" stickColor="black" ></Joystick>
</div>
<p>The current time is {currentTime}.</p>
<p>The access token is {accessToken}.</p>
</div>
烧瓶代码是
from __future__ import print_function
from flask import Flask, jsonify, request
from flask_cors import CORS
import time
from flask import Flask
import sys
robotIP="10.7.4.109"
PORT=9559
app = Flask(__name__)
access_token='a'
action="d"
@app.route('/time')
def get_current_time():
return {'time': time.time()}
@app.route('/login', methods=['POST'])
def nao():
nao_json = request.get_json()
if not nao_json:
return jsonify({'msg': 'Missing JSON'}), 400
action = nao_json.get('action')
access_token= action+'s'
print(access_token, file=sys.stderr)
return jsonify({'access_token': access_token}), 200
但是每次我 运行 他们两个,我都会收到 'msg': 'Missing JSON' 我已经定义的消息并且来自反应的数据在烧瓶中永远不可用,即使获取请求 works.I 我不确定我在这里做错了什么。
问题实际上是这是一个跨源请求,必须得到服务器的允许。
将此功能放在您的 Python 代码中:
@app.after_request
def set_headers(response):
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Allow-Methods"] = "*"
return response
注:
如果从同一台服务器提供 React,则没有必要。
您应该将这些 headers 的值设置为在生产中尽可能严格。上面的例子太宽容了。
您可以从 Flask 为您的 React 应用程序提供服务,因此不需要设置这些 headers。您可以使用类似这样的东西来提供主反应文件:
@app.route('/', defaults={'path': ''})
@app.route('/<string:path>')
@app.route('/<path:path>')
def index(path: str):
current_app.logger.debug(path)
return bp_main.send_static_file('path/to/dist/index.html')
其中 path/to/dist/index.html
将位于静态文件夹中。
查看更多信息: