Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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:

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!