简体   繁体   中英

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM