繁体   English   中英

节点应用程序不处理发布请求

[英]Node application not processing post request

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

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)
})

因此,当我单击一个按钮时,日志会显示在节点控制台中,但是在随机点击几次后,日志将停止显示并且浏览器中的控制台会显示错误,或者我尝试重新加载页面并且页面被卡住并重新加载节点应用程序没有进一步的响应。 如果我没有重定向到另一个页面,或者如果我在节点应用程序上实时处理请求,因为它们是从同一页面发出的,我是否需要发送不同的请求? 我仍在学习 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");
 })

暂无
暂无

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

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