How to send a POST request to the server from a single id page - Node JS

I have a ‘single product’ page that contains a form. I need to send a POST request to the server so I can add said ‘single product’ to the cart. When I try to send the POST request to the server, I encounter the following error in the browser:

  • Cannot POST /single-product/api/single/cart/products*

The form inside an ejs file looks like this:

<form action="api/single/cart/products" method="POST" onsubmit="addedToCart()">
        <input hidden value="<%= product.id %>" name="productId" />
        <input hidden value="<%= product.title %>" name="productTitle" />
        <input hidden value="<%= product.price %>" name="productPrice" />
        <button class="button has-icon is-inverted"
        style="background-color: #f15d8a;"
        >
          <i class="fa fa-shopping-cart"></i>&nbsp; Add to cart
        </button>
      </form>

The receiving end of the form action looks like this:

router.post("/single/cart/products", async (req, res) => {
const cookie = req.cookies;
const email = cookie.userEmail;
let cart;
const userId = await new AuthController().getId(cookie.userEmail);
let items = [req.body.productId, req.body.productTitle, req.body.productPrice]
let totalPrice = req.body.productPrice

await new CartController().record(userId, items, totalPrice, cookie.userEmail);

res.redirect('back');
});

How do I fix this error?

I think action and route do not match.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.