Flask Api working Half the time- works flawlessly when sending post with python but not with javascript

Question:

Hi I created an api that scrapes a website and returns values as a JSON file using python flask
For simple testing I set up a web Interface where the JSON is returned using that same API and it works flawlessly, but when I use the Javascript Fetch function in my react app to call it I keep getting different erros on the server side.

import requests
import json
data = {
    'act': '',
    'pw': '',
    'req': 'grades',
}

response = requests.post('http://127.0.0.1:5000/', data=data)
print(response.text)

This is they python code that workds perfectly

and here is the javascript code that is not working properly

  useEffect(() => {

    fetch('http://127.0.0.1:5000/', {
    method: 'POST',
    
    body: new URLSearchParams({
        'act': '',
    'pw': '',
    'req': 'grades'
    })
    }).then(response => {
      console.log('Response:', response)
      return response.json();
}).then(response => console.log(response))
  }, []); 

They are sending the exact Same request but getting different reponses

What it should look like(what I get when running the python code

What happens when I run the Javascript code

For refrence Here is the github repo with my API
https://github.com/amaheshwari01/POWERSCRAPER

EDIT: My Javascript code is written with react

Asked By: BillyBobJoe

||

Answers:

Looking at your API you are expecting a Form post. Try updating your JavaScript to use the FormData object and see if that works.

const formData = new FormData();

formData.append('act', '');
formData.append('pw', '');
formData.append('req', 'grades');

fetch('http://127.0.0.1:5000/', {
    method: 'POST',
    body: formData
})
.then(response => {
      console.log('Response:', response)
      return response.json();
}).then(response => console.log(response))

Answered By: Adam H