Search code examples
javascriptnode.jsexpressxmlhttprequesthttprequest

Node application not processing post request


My javascript file makes the following request everytime I click a button on a page (in Node using Express)

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

and this is supposed to catch the post request

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

so when i click a button the log is displayed in the node console but after a random number of clicks the log stops appearing and the console in the the browser displays an error or I try to reload the page and the page is stuck reloading along with no further responses from the node application. Is there a different request i need to send if I'm not redirecting to another page or if i'm processing requests on the node application live as they are being made from the same page? I'm still learning how http requests work so any feedback and tips are welcome.


Solution

  • Issue appears related to how you're setting up the url in the backend

    Try this instead

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

    Then front end would be

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

    This will work with the assumption that backend and front end are hosted in the same domain and port. If not, then you will need to add the proper domain and port to the front end that matches the backend hosted setup

    If you still want to utilize the : in the path then you can do the following

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

    And notice how the server now needs to support this by using double colon

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