reactjs 尝试从typescript获取键盘输入以发送到python文件[重复]

uplii1fm  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(309)

此问题在此处已有答案

How to enable CORS in flask(11个答案)
2天前关闭。
嗨,我正在写一个简单的代码,从 typescript 文件中获取键盘输入,并将其发送到一个单独的python文件中,它似乎在发送数据,因为每当我按WASD键或箭头键时,我会从python终端收到一条消息,看起来像这样。

  • 127.0.0.1 - - [2023年3月8日22:32:14]“选项/密钥HTTP/1.1”200 -*

我很确定我发送/接收它是正确的,但这是我第一次这样做,所以我不是100%肯定。有人能告诉我哪里出错了吗?我也很感激调试这些类型的文件的技巧,因为当试图调试python文件时。
以下是2个文件receive.py和App.tsx

接收.py

from flask import Flask, request

app = Flask(__name__)

@app.route('/key', methods=['POST'])
def handle_key_data():
    data = request.json
    key = data['key']
    is_pressed = data['isPressed']
    print(f"Received {key} key {'down' if is_pressed else 'up'} event")
    return 'Success'

if __name__ == '__main__':
    app.run(port=5000, debug=True)

应用程序tsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./App.css";

const apiUrl = "http://localhost:5000"; // API URL

const isValidKey = (key: string) => {
  return (
    ["W", "A", "S", "D"].indexOf(key.toUpperCase()) !== -1 ||
    ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(key) !== -1
  );
};

const App = () => {
  const [inputValue, setInputValue] = useState("");
  const [arrowValue, setArrowValue] = useState("");

  const handleKeyDown = (event: KeyboardEvent) => {
    if (isValidKey(event.key)) {
      sendData(event.key, true); // Send data when key is first pressed down
      if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(event.key) !== -1) {
        setArrowValue(event.key);
      } else {
        setInputValue(event.key);
      }
    }
  };

  const handleKeyUp = (event: KeyboardEvent) => {
    if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(event.key) !== -1) {
      setArrowValue("");
    } else {
      setInputValue("");
    }
    sendData(event.key, false); // Send data when key is released
  };

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, []);

  function sendData(key: string, isPressed: boolean) {
    const data = JSON.stringify({
      key: key,
      isPressed: isPressed
    });
    axios
      .post(`${apiUrl}/key`, data, { 
        headers: { 'Content-Type': 'application/json' }
      })
      .then((response) => {
        console.log("Data sent successfully");
      })
      .catch((error) => {
        console.error("Error sending data:", error);
      });
  }
  

  return (
    <div>
      <p>
        Press any of the following keys: W, A, S, D, ArrowUp, ArrowDown, ArrowLeft, ArrowRight
      </p>
      {(inputValue !== "" || arrowValue !== "") && (
        <p>
          You are holding down: {inputValue}
          {arrowValue !== "" ? ` + ${arrowValue}` : ""}
        </p>
      )}
    </div>
  );
};

export default App;
yqkkidmi

yqkkidmi1#

对不起,我应该在网上多看看,但我找到了解决方案,问题是浏览器最初发送一个OPTIONS请求与CORS请求,以检查是否允许进行实际的POST请求。这是我修改后的代码。

收到.py

from flask import Flask, request
from flask_cors import CORS
import json

app = Flask(__name__)
CORS(app)

@app.route('/key', methods=['POST', 'OPTIONS'])
def handle_key_data():
    if request.method == 'OPTIONS':
        response = app.response_class(
            status=200,
            mimetype='application/json'
        )
    else:
        data = request.json
        print(f"Received {data['key']} key {'down' if data['isPressed'] else 'up'} event")
        response = app.response_class(
            status=200,
            mimetype='application/json'
        )
        
    return response

if __name__ == '__main__':
    app.run(port=5000, debug=True)

我仍然很感激任何关于如何调试 flask 程序的提示。

相关问题