简体   繁体   中英

How to pass input data from ReactJS to Flask-Python (Backend)

I'm trying to build a directory website with ReactJS as a frontend and Python Flask as a backend. I'm trying to pass the text inputs in my searchbar.js to my Python script but I cant find a way to display the data that I've passed from the frontend in my backend to make sure I've really passed the data.

Here's my searchbar.js where I tried storing the data in a variable and had that passed to the api route i've made in python.:

function SearchBar() {
  const [searchedText, setSearchedText] = useState("");
  let navigate = useNavigate();

  const onSearch = () => {
    navigate(`/search?q=${searchedText}`);
    fetch('/ML/search',{
      method: 'POST',
      body: JSON.stringify({
        content:searchedText
      })
    })
  };
  return (
    <div>
      <Input.Search
        placeholder="Enter keyword..."
        onChange={(e) => {
          setSearchedText(e.target.value);
        }}
        onSearch={onSearch}
        onPressEnter={onSearch}
        enterButton></Input.Search>
    </div>
  );
}
export default SearchBar;

here's my api route in python for fetching the data that was passed from my frontend:

@app.route('/ML/search', methods=['POST'])
def search():
    request_data = json.loads(request.data)
    searchData = request_data['content']
    return searchData

So basically what I want to happen is I want to pass the input in my searchbar.js to my Python backend and store it as a variable so I could use that variable to search a column in SQL

You can use below code to print the data back to console.

  const onSearch = () => {
    navigate(`/search?q=${searchedText}`);
    fetch('/ML/search',{
      method: 'POST',
      body: JSON.stringify({
        content:searchedText
      })
    }).then(response => response.json()
      .then(data => ({ data, response })))
      .then(({ data, response }) =>  {
        console.log(data)
      })
  };



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM