Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

app.post("/mail", function(req, res) {
   console.log(req.body.name);
   console.log(req.route);
   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:

app.use(express.bodyParser()); 

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

Happy holidays! // Sam

like image 966
user1915666 Avatar asked Nov 13 '22 14:11

user1915666


1 Answers

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

app.use(express.bodyParser());

app.post('/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.

like image 197
theabraham Avatar answered Nov 15 '22 06:11

theabraham