1

I use FastAPI with Python to run the backend of the server. I am trying to connect the local frontend client with the local backend server. I am able to submit a POST request and the server, the server is being updated with new data (URL, password, shortened URL). I use axios() to POST my request, and use .then to get the response and update selected element.

My issue comes from the frontend receiving the data, then updating my <h1> element and console.log() the JSON data before immediately refreshing, removing or undoing all changes.

Server POST: http://127.0.0.1:8000/url

My frontend portion

    <form id="myForm">
        <label for="inputField">Enter your URL:</label>
        <input type="text" id="inputField" name="url" required>
        <button type="submit">Submit</button>
    </form>
    <h1 id="short_url"></h1>

    <script>
        const form = document.getElementById("myForm");
        form.addEventListener("submit", async (event) => {
            event.preventDefault();
            const formData = new FormData(form);
            const longURL = formData.get("url");
            axios
                .post(
                    "http://127.0.0.1:8000/url",
                    { target_url: longURL },
                    {
                        headers: {
                            "Content-Type": "application/json",
                        },
                    }
                )
                .then(function (response) {
                    console.log(response.data.admin_url);
                    document.getElementById("short_url").textContent = response.data;
                });
        });
    </script>

My backend portion where the POST request happens

@app.post("/url", response_model=schemas.URLInfo)
def create_url(url: schemas.URLBase, db: Session = Depends(get_db)):
    if not validators.url(url.target_url):
        raise_bad_request(message="Your provided URL is not valid")

    db_url = crud.create_db_url(db=db, url=url)
    return get_admin_info(db_url)

I have tried using return false at the end of frontend, using fetch() instead of axios(), expecting the update to stick but result is still the same, instant refresh of less than 1~5 seconds.

I have also tried using setTimeout(), but the speed at which it refresh is still the same.

What was successful was purposefully causing an error, it would no longer refresh but immediately following that, if I add in a proper URL, it would refresh the whole webpage.

Lastly, I have checked my database every POST request and it is constantly being updated with new data that I input.

Thank you in advance.

  • Related answers that you might find helpful can be found [here](https://stackoverflow.com/a/73358937/17865804), as well as [here](https://stackoverflow.com/a/71665594/17865804) and [here](https://stackoverflow.com/a/74338314/17865804) – Chris Apr 08 '23 at 06:29

0 Answers0