简体   繁体   中英

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.

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

I would add ending request processing code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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