Home > Enterprise >  How to run python scripts on button click in React?
How to run python scripts on button click in React?

Time:10-04

I don't know how to run .py file on clicking a button in ReactJS . All i want is to fetch the data created by the .py file using flask on clicking a button in React application . I set up a link on that button which will redirect to another webpage on which i want to display that fetched data. The React app and the .py file are on the same machine. I have no idea on how to do this . My app.js file in React app runs on "http://localhost:3000"

const onClickHandler = () => {
//fetching the data from the server  localhost:5000/page_name
  const url = "http://localhost:5000/data";
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");

 
    try {
      const res = await fetch(url);
      const data = await res.json();
      console.log(data);
      setName(data.name);
      setPassword(data.password);
    
    } catch (error) {
      console.log(error);
    }
  };

  return(
    <div>
    <button onClick={onClickHandler}>Click me</button>
        {name}
    {password}
    </div>
  );

My .py file runs on "http://localhost:5000/my_link"

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/data',methods=['GET', 'POST'])
def my_link():
  print("I got Clicked")
  return {'name': "geek", "password": "This is PWD"}
  

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

CodePudding user response:

If you have a bit of a misunderstanding of how api work.

Fist you should jsonify your data so wrap your return with jsonify.

return jsonify({'name': "geek", "password": "This is PWD"})

Then before doing anything fancy access your endpoint at /data and see if any data is there... should be or check your code.

If everything work then try :

   fetch('http://localhost:5000/data')
  .then((response) => response.json())
  .then((data) => console.log(data));

Should return some data.

Before jumping into React you should understand api and the fetch library.

  • Related