Posting Jquery Data to Express

No matter what combination of req.params/req.query/req.body and $.post({..} I use, I am unable to extract JSON data from my Jquery post request in express.

This is my jQuery:

$.post("/mail", {email : "[email protected]", name : "[email protected]"});

I have also tried various permutations of:

$.ajax({type: "POST", url: "/mail", dataType :"json", data :
{email : "[email protected]", name : "[email protected]"}}); 

This is my node.js express code:"/mail", function(req, res) {
   console.log("params1: " + req.param.params);

I have tried endless ways of accessing the data email and name without success. I'd be surprised if the solution were a simple modification to req.body/ req.params but anything is possible! The data just ain't there! (It does not appear in my url either -- all I see is localhost:1337)

req.body / req.params / req.param.params / req.params all return undefined and req.query returns [].

req.route returns:

{ path: '/mail',
  method: 'post',
  callbacks: [ [Function] ],
  keys: [],
  regexp: /^\/mail\/?$/i,
  params: [] }

I've tried adding:


But, admittedly, I do not fully understand its purpose. Any help is greatly appreciated.

Happy holidays! // Sam

You'll have to add the bodyParser() middleware before any routes that use it, like so:

app.use(express.bodyParser());'/mail', function(req, res) {
    console.log(req.body); // the body attribute will be created by the bodyParser()

The way express works is that each request is trickled down through your middleware and routes in the order that they're declared. Since the bodyParser() middleware is now declared before your route, it'll have a chance to parse the body of the request into a nice JSON format, stick that parsed value into req.body, and then pass on control to the next route/middleware; otherwise, req.body will simply not exists.