简体   繁体   English

查询参数从 POST 请求中丢失(nodeJS 和 Express)

[英]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.我第一次尝试使用 REST API 使 JavaScript 客户端和 nodeJS 服务器与 Express 进行通信。出于某种原因,我在xhttp.send中提供的任何参数在到达后端时都会丢失。

In the client side I have the following function:在客户端,我有以下 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 ?查询参数 go 在 URL 之后? 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.当您发出 POST 请求时,您传递给send()的值将在请求正文中发送,如果(根据文档)您设置了合适的正文解析中间件,则可以通过req.body访问该正文。

You should also set a Content-Type request header to tell the server how to parse the body you are sending it.您还应该设置一个Content-Type请求 header 来告诉服务器如何解析您发送的正文。 XMLHttpRequest will do that automatically if you pass it a URLSearchParams object instead of a string.如果您传递URLSearchParams object 而不是字符串, XMLHttpRequest将自动执行此操作。


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.综上所述,您正在发出 Ajax 请求,然后立即重新加载页面。

The point of Ajax is to make requests without reloading the page. Ajax 的要点是在重新加载页面的情况下发出请求。

You might as well use a regular <form> submission instead.您也可以改用常规<form>提交。 It would be simpler.这会更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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