Hello:
According to the doc, it seems like it only mentions that agent is able to store the cookie and persist its with the second request.
However what i wanna implement is: After login request, i store my jwt token in my cookie and send the Set-Cookie header to client, and then i wanna perform the second request and for this request i need to grab the token i stored in my agent cookie and set it in the Authentication header.
I look at the doc and there seems no such way like agent.getCookie(cookieName: string) to directly get the cookie, so is there anyway to do this? My English is not very well and i hope i explain my confusion clearly.
Cheers!
I actually found a solution here. It manually store the cookie in a variable after login:
const agent = request.agent(api);
let cookie;
beforeAll(() => agent
.post('/login')
.send({
username: testerName,
password: testerPassword,
})
.expect(200)
.then((res) => {
const cookies = res.headers['set-cookie'][0].split(',').map(item => item.split(';')[0]);
cookie = cookies.join(';');
}));
describe('GET logout', () => {
it('logs user out', () => agent
.get('/logout')
.set('Cookie', cookie)
.expect(302));
});
Not sure if this is the correct way to implement this, any ideas?
You were almost correct to start with. The cookies are stored in agent.jar and you can access them through agent.jar.getCookie(cookie_name, access_info) (see https://github.com/bmeck/node-cookiejar )
So, you need to match not just on the cookie name but also access info. You can use the CookieAccessInfo function to create an access info object, with this you can match on e.g specific paths and domains.
const { CookieAccessInfo } = require('cookiejar')
...
await myagent
.post('/api/auth/login')
.send({ user: 'test', pass: 'test'})
.set('Accept', 'application/json')
.expect('set-cookie', /connect.sid=.*; Path=\/; HttpOnly/)
.expect(200)
const access_info = CookieAccessInfo() // can provide path, etc also...
const cookies = myagent.jar.getCookie('connect.sid', access_info)
Not sure this is the intended way to do it but I think this is quite clean...
Sweet, This is exactly what i am looking for. Thanks for your detailed explanation.
Most helpful comment
You were almost correct to start with. The cookies are stored in
agent.jarand you can access them throughagent.jar.getCookie(cookie_name, access_info)(see https://github.com/bmeck/node-cookiejar )So, you need to match not just on the cookie name but also access info. You can use the CookieAccessInfo function to create an access info object, with this you can match on e.g specific paths and domains.
Not sure this is the intended way to do it but I think this is quite clean...