POST 请求中查询参数丢失(nodeJS 和 Express)
我第一次尝试使用 REST API 让 JavaScript 客户端和 NodeJS 服务器与 Express 进行通信。由于某种原因,我在 xhttp.send 中给出的任何参数在到达后端时都会丢失。
在客户端,我具有以下功能:
function changeStatus(station) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api", false);
xhttp.send(`station=${station}`);
window.location.reload();
}
在服务器端,我具有以下功能:
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");
}
});
无论如何,我都会获得“其他”配置。有什么建议吗?我也不知道如何记录要附加的原始请求。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查询参数不会丢失。它们不存在。查询参数位于路径段后面的
?
之后的 URL 上。当您发出 POST 请求时,您传递给
send()
的值将在请求 body 中发送,该请求可通过req.body
访问,如果(根据文档)您已经设置了合适的正文解析中间件。您还应该设置一个
Content-Type
请求标头来告诉服务器如何解析您发送的正文。如果您向 XMLHttpRequest 传递一个URLSearchParams
对象而不是字符串,XMLHttpRequest
将自动执行此操作。客户端代码
服务器端代码
综上所述,您正在发出 Ajax 请求,然后立即重新加载页面。
Ajax 的要点是在不重新加载页面的情况下发出请求。
您也可以使用常规的
The query parameters aren't being lost. They don't exist. Query parameters go on the URL after a
?
after the path segment.When you make a POST request, the value you pass to
send()
is sent in the request body which is accessible viareq.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 aURLSearchParams
object instead of a string.Client-side code
Server side code
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.