Last Updated: February 25, 2016
·
1.625K
· 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/

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside