Search code examples
javascriptformspostfetch

best practise to send form information to server


I am having a hard time getting more into the POST method - my teacher set up a server, but it doesn't seem to accept the data I'm sending through. Would the following be an acceptable way of sending my 2 inputs with the type of text? Or is there another standardized way of doing this?

For the sake of the example, my input fields would be first and last name. Nothing crazy.

document.getElementById("myForm").addEventListener("submit", async (e) => {
    e.preventDefault();

    await fetch("http://localhost:3000/course/add", {
        method: "POST",
        headers: {
            "Content-Type": "multipart/form-data",
        },
        body: new FormData(e.target),
    })
        .then((confirm) => confirm.json())
        .catch((err) => err)
        .then(
            (response) =>
                (document.getElementById("container").innerHTML = response.message)
        );
});

Solution

  • Why it's not working is hard to say without knowing the API implementation. Some pointers for debugging:

    • Check your network tab in F12. Does the request fire (if not, the issue may be with the element selector or the event listener)? Does it hang (server side issue with possibly data input, route or internal behavior) or does it generate a response (if so, what response)? What is the POST response code and body?
    • Check the API which you seem to be running locally. You should expect that your teacher built (at least some rudimentary) logging into the server, so that any errors must be visible there.
    • Also check the console in F12. Any issues should be visible there.
    • More generally, you seem to be writing your frontend in vanilla JavaScript. Today, it is common to write your frontends using a framework like React, Vue, Angular or Svelte; vanilla JS is more and more uncommon. For further learning, it can be worthwhile to take a look at these frameworks as well.