简体   繁体   中英

couldn't set cookie from frontend react

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.

On the front end, set the allow-credentials header to true, and on the api, set Origin-Allow-Credentials header to true, save then restart your server.And then after saving the front-end, left click on the browser reload icon on your website, "click on hard reload and delete cache". Then retry.

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