节点应用程序未处理 post 请求

Node application not processing post request

我的 javascript 文件每次单击页面上的按钮时都会发出以下请求(在使用 Express 的节点中)

toggleCartItem = index => {
    http = new XMLHttpRequest();
    http.open("POST", `/cart_item/${index}`, true);
    http.send();
}

这应该会捕获 post 请求

app.post("/cart_item/:index", (req, res) => {
    console.log("order id:",req.params.index)
})

因此,当我单击一个按钮时,日志会显示在节点控制台中,但在随机点击几次后,日志会停止显示,并且浏览器中的控制台会显示错误,或者我尝试重新加载页面和页面卡在重新加载中,节点应用程序没有进一步响应。如果我没有重定向到另一个页面,或者如果我在节点应用程序上实时处理请求,因为它们是从同一页面发出的,我是否需要发送不同的请求?我仍在学习 http 请求的工作原理,因此欢迎任何反馈和提示。

出现的问题与您在后端设置 url 的方式有关

试试这个

 app.post("/cart_item/:index", (req, res) => {
    console.log("order id:",req.params.index)
    res.json();
 })

那么前端就是

 toggleCartItem = index => {
    http = new XMLHttpRequest();
    http.open("POST", `/cart_item/${index}`, true);
    http.send();
 }

这将假设后端和前端托管在同一域和端口中。如果没有,那么您需要将正确的域和端口添加到与后端托管设置相匹配的前端

如果您仍想在路径中使用 : 则可以执行以下操作

toggleCartItem = index => {
    http = new XMLHttpRequest();
    http.open("POST", `/cart_item:${index}`, true);
   http.send();
}

并注意服务器现在需要如何使用双冒号来支持它

 app.post("/cart_item/::index", (req, res) => {
    console.log("order id:",req.params.index)
    res.json();
 })

我会添加结束请求处理代码:

app.post("/cart_item/:index", (req, res) => {
    console.log("order id:",req.params.index);
    res.send("OK");
 })