0

so I have this line in front page:

var x = "Hi";
var y = 123;

xhttp.open("POST", "/toNodeServer", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

         
  
  xhttp.send(x, y);

and in the server I have the following:

outer.post('/toNodeServer', function(req, res, next){
 
  var x = req.body


console.log(x);

so the result is it does not send y value, I got this from the terminal: {'Hi': ''}

can anyone please explain what is going on and how to send these two variables?

1 Answer 1

1

XMLHttpRequest.send(body) only takes 1 parameter.

You need to post a JSON or send an url-encoded string (or any other serialized string)

JSON

xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify({ x: x, y: y}));

x-www-form-urlencoded

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`x=${x}&y=${y}`);

If you're sending JSON, don't forget to add:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

Then you will be able to access it this way:

const x = req.body.x;
const y = req.body.y;

Or using destructuring:

const { x, y } = req.body;
Sign up to request clarification or add additional context in comments.

11 Comments

I am using bodyParser, but how to access each one of these variable from the server? as req.body is only picking the first variable in xhttp.send(x,y);
req.body.x; is causing error I dont know why, I have to use req.body only. using this: const { x, y } = req.body; is not getting me right values
Show your updated code, my code example works fine, you're doing something wrong. Post server & client code.
client side: xhttp.send(JSON.stringify({ x: x, y:y}));
server side: const x = req.body.x; const y = req.body.y;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.