Search code examples
node.jsmongodbformsexpressresponse

How can i send a form with node.js without the web starts loading?


Sorry for my bad english, i'm studying to improve it.

I'm new in node.js and i want to send many forms to a mongoDB database without the web starts loading something and never stop, i think it's searching the response and isn't exist a response (and i don't want to send a response, i only want to send forms) I can send all of i want and works correctly, but i think is not tidy that that occurs. In the moment i press the submit button, the web starts loading like this.

index.ejs: i have a form with method="POST" and action="/addProduct"

routes.js: router.post('/addProduct', controller.addProduct)

controllers.js: export const addProduct = async (req) => { const newProduct = Product(req.body); -> mongoose model await newProduct.save();

Thanks!

I tried different ways but i can't resolve this


Solution

  • Make xhr requests to avoid page loading.

    in your form make the submit button type as button:

    <form>
      ///form input element
      <label for="fname">First name: </label>
      <input type="text" id="fname" name="fname"><br><br>
      <input type="submit" value="Submit" onclick="postForm()">
    </form> 
    
    <script>
    function postForm(){
    let field1 = document.getElementById("fname").value
    fetch('http://localhost:3000/post/addProduct', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ "field1": field1 })
    })
       .then(response => response.json())
       .then(response => console.log(JSON.stringify(response)))
    }
    </script>
    

    then get the form data in req.body.field1 in your /post/addProduct route. Make sure you are using body parser properly.