Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!