首页 > 解决方案 > 从反应到烧瓶的发布请求

问题描述

我正在尝试使用以下代码从 react 向烧瓶发送发布请求:

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' 消息,并且来自 react 的数据在烧瓶中永远不可用,即使 get 请求有效。我不确定我在做什么这里错了。

标签: pythonreactjsflaskflask-restful

解决方案


问题实际上是这是一个必须由服务器允许的跨源请求。

将此函数放在您的 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

笔记:

  • 如果反应是从同一台服务器提供的,这将是不必要的。

  • 您应该将这些标头的值设置为在生产中尽可能严格。上面的例子太宽松了。


您可以从 Flask 提供您的 React 应用程序,因此不需要设置这些标头。您可以使用这样的东西来提供主要的反应文件:

@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

更多信息请访问:


推荐阅读