I'm trying to write a test where SuperAgent calls multiple (sub)domains, where cookies should be shared between them. Therefore, I want to swtich the agent dynamically, ie I can't create a new agent because I want the agent to retain cookies throughout.
agent = request.agent("https://example1.com")
agent.get('/path')
agent.changeHost("https://example2.com") // Fake. How to actually do this?
agent.get('/path') // Now we are retrieving same path from a different host
(syntax based on agency.js example)
I've also tried absolute URLs, ie agent.get('https://example1.com/path')
, but that apparently isn't supported (Uncaught TypeError: Cannot read property 'address' of undefined
).
I didn't arrive to reproduce the error : Uncaught TypeError: Cannot read property 'address' of undefined
.
But, i tried with 3 node.js server and it works for me like that (with absolute path) :
// SERVER -> localhost:3000
// ----------
var express = require('express');
var app = express();
var sp = require('superagent');
app.get('/', async function(req, res, next) {
var agent_1 = sp.agent();
await agent_1.post('http://localhost:4000').send({test_cookie: true});
await agent_1.get('http://localhost:4000');
await agent_1.get('http://superagent.test:5000');
res.json({});
});
app.listen(3000, function() { console.log('App running'); });
// SERVER -> localhost:4000
// ----------
var express = require('express');
var app = express();
// cookie / body parser code removed...
app.get('/', function(req, res, next) {
if (req.cookies.hw) { console.log('localhost 4000 : cookie -> ' + req.cookies.hw); }
res.json({success: 'get'});
});
app.post('/', function(req, res, next) {
if (req.body.test_cookie) { res.cookie('hw', 'Hello, World!'); }
res.json({success: 'post'});
});
app.listen(4000, function() { console.log('App running'); });
// SERVER -> superagent.test:5000
// ----------
var express = require('express');
var app = express();
// cookie / body parser code removed...
app.get('/', function(req, res, next) {
if (req.cookies.hw) { console.log('superagent.test 5000 : cookie -> ' + req.cookies.hw); }
res.json({success: 'get'});
});
var appp = express();
var vhost = require('vhost');
appp.use(vhost('superagent.test', app));
appp.listen(5000, function() { console.log('App running'); });
The possible reason could be that superagent uses asynchrone methods. It works only if i use async / await (or .then()).
With the code above, i have the cookie on each server with the same agent. Let me know if i understood well your question and if it solves your problem.