Last Updated: February 25, 2016
·
1.341K
· piatra

POST submission to Nodejs in vanilla js

The title might not be to descriptive, but what I want to show how I send data in a POST request to Nodejs without jquery or any other library. I've required this many times and I always get something wrong.

// this simulates an html form
var formdata = new FormData(); [1]
formdata.append('param_name1', 'value')
formdata.append('param_name2', 'value')    
formdata.append('param_name3', 'value')
var xhr = new XMLHttpRequest(); // create a xhr [2]
xhr.open('POST', '/post', true);
xhr.onload = function(e) { 
    if (this.status == 200) { 
       console.log(this.responseText); 
    }
};
xhr.send(formdata); // send the data 

And a very important part is to have you app configured in this order

app.use(express.bodyParser());
app.use(app.router); 

First the bodyParser and then the router
And the params are in the req.body.param_name1, 2, 3 etc.

[1] https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData

[2] http://www.html5rocks.com/en/tutorials/file/xhr2/