Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query parameters are lost from POST request (nodeJS & Express)

I’m trying for the first time to make a JavaScript client and nodeJS server with Express communicate using REST API. For some reason, any parameter I give in xhttp.send is lost when arriving the back-end.

In the client side I have the following function:

function changeStatus(station) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "/api", false);
  xhttp.send(`station=${station}`);
  window.location.reload();
}

And in the server side the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.post("/api", function (req, res) {
  if ("station" in req.query) {
    db[req.query.station] = !db[req.query.station];
    res.send(
      `Station ${req.query.station} changed to ${db[req.query.station]}`
    );
  } else {
    res.send("No station specified");
  }
});

In any case I get the ‘else’ configuration. Any suggestion on what to do? I also can’t figure out how to log the raw request to attach.

>Solution :

The query parameters aren’t being lost. They don’t exist. Query parameters go on the URL after a ? after the path segment.

http://example.com?this=is&a=set&of=query&parameters=!

When you make a POST request, the value you pass to send() is sent in the request body which is accessible via req.body if (as per the documentation) you have a suitable body-parsing middleware set up.

You should also set a Content-Type request header to tell the server how to parse the body you are sending it. XMLHttpRequest will do that automatically if you pass it a URLSearchParams object instead of a string.


Client-side code

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api", false);
const body = new URLSearchParams();
body.append("station", station);
xhttp.send(body);
window.location.reload();

Server side code

app.use(express.urlencoded());

app.post("/api", function (req, res) {
    if ("station" in req.body) {

All that said, you are making an Ajax request and then immediately reloading the page.

The point of Ajax is to make requests without reloading the page.

You might as well use a regular <form> submission instead. It would be simpler.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading