|
import express from 'express'; |
|
import superagent from 'superagent'; |
|
import Cookies from 'cookies'; |
|
|
|
const app = express(); |
|
|
|
app.get('/set-cookies', function (req, res) { |
|
const cookies = new Cookies(req, res); |
|
cookies.set('cookie_with_domain', 'with_domain', { domain: 'localhost' }); |
|
cookies.set('cookie_without_domain', 'without_domain'); |
|
res.status(200).end(); |
|
}); |
|
|
|
app.get('/set-cookies-and-redirect', function (req, res) { |
|
const cookies = new Cookies(req, res); |
|
cookies.set('cookie_with_domain', 'with_domain_in_redirect', { domain: 'localhost' }); |
|
cookies.set('cookie_without_domain', 'without_domain_in_redirect'); |
|
res.redirect('/read-cookies'); |
|
}); |
|
|
|
app.get('/read-cookies', function (req, res) { |
|
const cookies = new Cookies(req, res); |
|
const withDomain = cookies.get('cookie_with_domain'); |
|
const withoutDomain = cookies.get('cookie_without_domain'); |
|
res.json({'cookieWithDomain': withDomain, 'cookieWithoutDomain': withoutDomain}); |
|
}); |
|
|
|
app.listen(8080, async () => { |
|
try { |
|
// 1. Create an agent |
|
const agent = superagent.agent(); |
|
|
|
// 2. Set a cookie in a standard response (without a redirect) |
|
await agent.get('http://localhost:8080/set-cookies'); |
|
const response = await agent.get('http://localhost:8080/read-cookies'); |
|
console.log(response.body); |
|
|
|
// 3. Try to set the same cookie in a followed redirect |
|
const redirectResponse = await (agent.get('http://localhost:8080/set-cookies-and-redirect').redirects(1)); |
|
console.log(redirectResponse.body); |
|
} finally { |
|
process.exit(0); |
|
} |
|
}); |