-1

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

  • Is your endpoint expecting JSON or a Form post? If it's JSON then use [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) when setting your body. – Adam H Mar 06 '23 at 21:42
  • what do you mean by that... I am just outputting what I get from the api to console, then I copied the object and put it in a json file to view – BillyBobJoe Mar 06 '23 at 21:46
  • I mean the handler, written in Python, is expecting the data to be a Form posted to it. The way you are using [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams) wont work as the constructor of that object does not accept JSON. – Adam H Mar 06 '23 at 21:50

1 Answers1

0

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))
Adam H
  • 1,750
  • 1
  • 9
  • 24