I have a backend node server, that has two apis: to set and to get cookies.
Backend code to set and get cookies:
Server : localhost:4001
router.get("/addCartToCookie", function(req, res){
let options = {
maxAge: 1000 * 60 * 15,
httpOnly: true,
};
let cartData = {
name: req.body.name,
slug: req.body.slug,
productPictures: req.body.productPictures,
price: req.body.price,
description: req.body.description,
quantity: req.body.quantity,
};
// Set cookie
res.cookie("cartName", cartData, options); // options is optional
res.send("Cart Added to Cookie");
});
//To get the cookie
router.get("/getCartFromCookie",function(req, res){
res.send(req.cookies);
console.log(req.cookies["cartName"]);
});
Frontend react code to call the api on button click:
Client: localhost:3001
const addToCartCookie = () => {
console.log("Calling add to cart cookie");
axios
.get("http://localhost:4001/api/addCartToCookie", {
name: product.name,
slug: product.slug,
productPictures: product.productPictures[0].img,
description: "sabdsjbfjsd",
price: product.storePrice,
quantity: itemCount,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
OnClick calls the above api,
<Button
type="primary"
onClick={() => {
addToCartCookie();
}}
>
ADD TO CART
</Button>
It doesn't set a cookie in the client browser upon the button click. While checking the network tab, the api is called fine but the only problem is that it is not setting the cookie on to client side.