0

index.html:

//display the searched laptop
function searchProducts(){
    let search = document.getElementById("laptopSearched").value;
    console.log("Search_Value " + search);
 
    const formData = new FormData();

    formData.append('mySearch', search);

    //Create request object 
    let request = new XMLHttpRequest();

    //Set up request with HTTP method and URL 
    request.open("POST", "/laptops");

    //Send request
    request.send(formData);

}

server.js

 app.post('/laptops', function(request, response){
   //get laptop searched by user
   let laptopBrand = request.body.mySearch;
   console.log(laptopBrand);
 });

When request.body.mySearch is read on the server side, an undefined value is returned. How should this problem be solved please?

Phil
  • 157,677
  • 23
  • 242
  • 245
MDB
  • 51
  • 5
  • 1
    Using `FormData` posts the request as `application/x-www-form-urlencoded`. You need special middleware like Multer to handle that. Instead of `FormData`, use `URLSearchParams` and make sure you've registered the `express.urlencoded()` middleware – Phil Dec 11 '22 at 04:39
  • Does this answer your question? [new FormData() "application/x-www-form-urlencoded"](https://stackoverflow.com/questions/7542586/new-formdata-application-x-www-form-urlencoded) – Phil Dec 11 '22 at 04:41
  • Thank you very much. I have been able to solve the issue with the help of your suggestions. – MDB Dec 11 '22 at 04:48

0 Answers0