簡體   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