Search code examples
javascriptnode.jsajaxexpress

Sending FormData using AJAX to nodejs + express server


Here is my frontend JS. As a side note, FormData.append() does not work, so I have to set its properties explicitly. @data is an object with input name: value properties.

function http(data) {
 
   const httpData = new FormData();
    for (let prop in data) {
        httpData[prop] = data[prop];
    }
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {

        if (this.readyState === 4) {
            const status = this.status;
            const data = this.responseText;

        }
    };
    xhttp.open('POST', '/api/login');
    xhttp.setRequestHeader('Content-Type', 'x-www-form-urlencoded');
    xhttp.send(httpData);
}

And on the server side

app.use(express.urlencoded({
    extended: true
 }));

express ready to parse form data, and in the /routes/api.js (I am using express router)

router.post('/login', (req, res, next) => {

    console.log(req.body);
    res.end();
});

I got req.body as an {}

Where did I go wrong?


Solution

  • You have three problems.

    1. append() does work. It just doesn't store the data in a way that shows up with console.log. Assigning arbitrary properties doesn't work.
    2. You need to send the correct Content-Type header. This is multipart/form-data with a mandatory boundary parameter that you have no way of knowing. Don't try to set the Content-Type header manually. XMLHttpRequest will generate it automatically from the FormData object.
    3. You need a body parser for Express that supports multipart/form-data. The built-in one does not. The documentation for it on npm suggests 4 alternatives.