Search code examples
javascriptnode.jsformsexpressxmlhttprequest

Issue on simple xmlhttprequest with post data to expressjs


  • Using nodejs, xmlhttprequest for simple Form post data.

  • Using formdata() constructor to get the values from html. But in

  • expressjs, the request body is not getting properly. It throws the
    below error. What would be the issue on posting data through the
    below code.

Html:

> <form id='loginForm'>
>       <div>
>         <label>Username:</label>
>         <input type="text" name="title" />
>         <br/>
>       </div>
>       <div>
>         <label>Password:</label>
>         <input type="password" name="descr" />
>       </div>
>       <div>
>         <input type="submit" value="Submit" />
>       </div>
>     </form>

Scripts:

window.onload = function () {
var testForm = document.getElementById('loginForm');
testForm.onsubmit = function(event) {
    event.preventDefault();
    const XHR = new XMLHttpRequest();
    var formData = new FormData(testForm);
    XHR.open( "POST", "http://localhost:5000/addCat", true);
    XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    XHR.send(formData);
}
}

But in expressjs call:

const addCategories = (request, response) => {
  const { title, descr } = request.body
  console.log(request.body);

// output: { '------WebKitFormBoundaryxBFmvN6Sw8QT3BA7\r\nContent-Disposition: form-data; name': '"title"\r\n\r\nsdsf\r\n------WebKitFormBoundaryxBFmvN6Sw8QT3BA7\r\nContent-Disposition: form-data; name="descr"\r\n\r\nsdfdsfds\r\n------WebKitFormBoundaryxBFmvN6Sw8QT3BA7\r\nContent-Disposition: form-data; name="title"\r\n\r\nnewtitle\r\n------WebKitFormBoundaryxBFmvN6Sw8QT3BA7\r\nContent-Disposition: form-data; name="descr"\r\n\r\ngoind descriptions\r\n------WebKitFormBoundaryxBFmvN6Sw8QT3BA7--\r\n' }


  client.query('INSERT INTO categoryLists (title, descr) VALUES ($1, $2)', [title, descr], (error, results) => {
    if (error) {
      throw error
    }
    response.status(201).send(`User added with ID: ${results.insertId}`)
  })
};

Getting Error: error: null value in column "title" violates not-null constraint


Solution

  • You've said:

    XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    

    … but FormData objects generate multipart formatted requests, not urlencoded ones.

    Remove that line. Let XHR generate its own Content-Type header from the FormData object.


    You also need to make sure that in your Express.js code you have a body parser capable of handling multipart data.