0

Hi I'm trying to write a simple code that takes a input on the keyboard from the typescript file and send it to a separate python file. It seems to be sending the data because I'm getting a message from the python terminal whenever I hit the WASD keys or the arrow keys I get a message that looks like this.

127.0.0.1 - - [08/Mar/2023 22:32:14] "OPTIONS /key HTTP/1.1" 200 -

I'm fairly certain I'm sending/receiving it right but this is my first time doing this so I'm not 100% sure. Could someone tell me where I'm going wrong. I'd also appreciate tips on debugging these types of files because when trying to debug the python file.

The following are the 2 files receive.py & App.tsx

receive.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)

App.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;

Sugar
  • 21
  • 6

1 Answers1

0

Sorry I should have looked online more but I found the solution, the problem was the browser initially sends an OPTIONS req with a CORS request to check if its allowed to make the actual POST req. This is my revised code.

recieve.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)

I'd still appreciate any tips on how to debug flask programs.

Sugar
  • 21
  • 6