0

I created a python API which returns based on the input one of three outputs: "Success (email already exists)" "Success" "Invalid Email"

I have atatched what the output looks like when called directly from a browser. So the issue is when I call this API in my code, it doesnt execute switching to another page and keeps showing a error message I created if the API returns "Invalid Email". It shows the error message and doesnt execute even if the API returns "Success". I know the API is working and returning the correct outputs as the API is executing the relative commands on some files. How can I fix this? Here is a snippet from my websites code.

      form.addEventListener('submit', (event) => {
        event.preventDefault();
        const formData = new FormData(form);
        const name = formData.get('name');
        const email = formData.get('email');
        const apiURL = `http://censored-for-privacy/?name=${name}&email=${email}`;

        fetch(apiURL)
          .then(response => response.text())
          .then(data => {
          if (data === 'Success (email already exists)' || data === 'Success') {
            window.location.href = 'main.html';
          } else if (data === 'Invalid Email') {
            errorMessage.style.display = 'block';
            form.reset();
          }
        })
        .catch(error => {
          console.error('Error:', error);
          errorMessage.style.display = 'block';
          form.reset();
        });
      });

I have tested the API and it works well, I tried changing 'main.html' to a url for google still doesnt work. It executes the alternate function. Found a fix....

Shab
  • 1
  • 3
  • Instead of concatenating query parameters manually, please use the [`URL` API](//developer.mozilla.org/en/docs/Web/API/URL) and its `searchParams` property, which [_correctly encodes_ parameters](/a/44160941/4642212): `const apiURL = new URL("http://censored-for-privacy/"); apiURL.searchParams.set("name", name); apiURL.searchParams.set("email", email); fetch(apiURL)`. How do you confirm that `data` really matches these exact strings? Is there a line break at the end? What do you mean by _“the alternate function”_? _“It shows the error message”_ — Which one? – Sebastian Simon Feb 19 '23 at 21:32
  • I modified the API to return a response code (200 / 400). Javascript seems to like that more then just text & now its working. – Shab Feb 20 '23 at 06:00

0 Answers0