Why do I get error 400 on http request when sending datas to API?

Viewed 50

Good morning everyone,

I have been struggling with a 400 error in my JS code.

API need to get contact object with all information from the form, and an array of products id to return an order number.

So I get all the values from the form and put them into the contact object. Then i need to get the products in the cart from a localstorage, get the id of all the objects inside the cart, put them into a products array to send to the API.

// Création de l'objet contact à l'envoi du formulaire
document.getElementById("form").addEventListener("submit", function() {
  let contact = {
    nom: document.querySelector("#nom").value,
    prenom: document.querySelector("#prenom").value,
    adresse: document.querySelector("#adresse").value,
    ville: document.querySelector("#ville").value,
    email: document.querySelector("#email").value
  }
  //Création du tableau de produits
  let panier = localStorage.getItem("panier");
  panier = JSON.parse(panier);
  let products = [];
  panier.produits.forEach(element => {
    products.push(element._id);
  })
  console.log(products);

  //Envoi des données à l'API
  let requete = new XMLHttpRequest();
  let url = 'http://localhost:3000/api/cameras/order';
  requete.open("POST", url);
  requete.setRequestHeader("Content-Type", "application/json");

  requete.addEventListener("load", function() {
    console.log(requete.responseText);
  })

  let envoi = JSON.stringify({contact,products});
  requete.send(envoi);
});
<!DOCTYPE html>
<html lang="fr" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <form id="form">
      <p>
      <label for="Nom"></label>
      <input type="text" name="Nom" value="Nom" id="nom" required>
      </p>
      <p>
      <label for="Prénom"></label>
      <input type="text" name="Prénom" value="Prénom" id="prenom" required>
      </p>
      <p>
      <label for="Adresse"></label>
      <input type="text" name="Adresse" value="Adresse" id="adresse" required>
      </p>
      <p>
      <label for="Ville"></label>
      <input type="text" name="Ville" value="Ville" id="ville" required>
      </p>
      <p>
      <label for="Email"></label>
      <input type="email" name="Email" value="Email" id="email" required>
      </p>
      <p>
      <input type="submit" name="submit" value="Commander">
      </p>
    </form>
    <script src="commande.js" charset="utf-8"></script>
  </body>
</html>

URL is correct for sure, and I really don't understand what i did wrong on this request.

Thank you for your help

Have a nice day and a nice week-end

0 Answers
Related