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?
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.