ladjs / superagent

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
https://ladjs.github.io/superagent/
MIT License
16.59k stars 1.33k forks source link

How to make superagent receive cookies from the server? #1579

Closed ghost closed 4 years ago

ghost commented 4 years ago

Hello! So I want to know how to receive cookies from the server using superagent. Here is how the code on my server looks like:

var router = require('express').Router();
// Please note: I am using express
router.post('/', function(req, res) {
    res.cookie('uname', req.body.key).send("Cookies are set!");
});
//
module.exports = router;

And here is how the code looks on the client-side:

superagent.post('http://localhost:5000/')
   .send({ key: "fragile", cat: "billy" })
   .set('accept', 'json')
   .end(function(err, res) {
        if (err) { console.error(err); }
        else { console.log(res); }
   });

I know that whenever a cookie gets set, a set-cookie header pops up. I even tried cross-referencing this stackoverflow question and #597 but it didn't help. Is there any way to make superagent receive cookies?

ghost commented 4 years ago

Looks like no one wants to respond!

sannajammeh commented 3 years ago

Cookies are already set for you when you make the request, as long as you on the server set the cookie on the response object. Make sure to add .withCredentials() when making your request. To retrieve the cookie you can simply use js-cookie or any other library. Js-cookie implementation.

   import Cookies from "js-cookie";

  // .... other code

  // Make request
  const response = await superagent.get(url).withCredentials();
  //
  console.log(Cookies.get("COOKIE_ID"));