0

I have 2 js files that correspond with each other, one for the server and one for the client. The client should use the post request named "/postGetInc", send a number to the server, the server increments it and returns the result. Whenever I try to post the specific number to the server it sees it as an empty object. I know that the input should also be an object, but when I make an object using {"number": number} it still doesn't recognize the number value.

So this is the little code on my server.js

app.post("/getInc", function (req, res) {
console.log("req: " + req);
console.log("req.number: " + req.number);

req.number++;
res.send(req.number);
});

and this is the function I use for the post, on the client.js

function postGetInc(number){
var res = "no response";
toSend = { "number": number };
$.post("/getInc", toSend, function (response) {
    console.log(response);
    res = response;
});
return res;
//this should return number+1
//in case of a failt, it returns "no response"
}

whenever I run postGetInc(10) I get

"no response" 

printed on my console.

on my server console I get:

req: [object Object]
req.number: undefined

If I replace {"number": number } with just number, and req.number with number, I get the same messages printed on my console.

Thanks for reading, I'd love to hear what I do wrong so please help me.

Sytze Andringa
  • 413
  • 1
  • 4
  • 12

1 Answers1

0

To access the parameter on the server side, you have to use req.body:

req.body.number

I recommend to read the documentation. Note that it's undefined by default and you have to register body parsers first:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

Another problem is that you can't return res from postGetInc. Please see How to return the response from an Ajax call? for reasons and solutions.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • so if I get it right, req represents all the information that is sent from the client to the server and not only an object? So also ip-adress etc – Sytze Andringa Dec 03 '14 at 17:36
  • Yep. An HTTP request contains also a lot of meta data. https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_message – Felix Kling Dec 03 '14 at 17:37
  • I changed every "req.number" with "req.body.number" This gives me a bunch of errors that it can't find the number value of undefined. If I add the 2 lines you provided and put them at the beginning of my server.js file, I get an error that it can't find the module when I start up the server. Where can I get this package, and is it absolutely needed to include this package if I want the same results? thanks for your replies – Sytze Andringa Dec 03 '14 at 17:53
  • As I said, `req.body` is undefined by default. yes it is needed. You probably get it via `npm install body-parser`. – Felix Kling Dec 03 '14 at 17:59