使用SuperAgent动态更改主机

时间:2018-09-26 09:39:02

标签: javascript node.js http superagent

我正在尝试编写一个测试,其中SuperAgent调用多个(子)域,并且应该在它们之间共享cookie。因此,我想动态处理代理,即,由于希望代理始终保留cookie,所以无法创建新代理。

  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

(基于agency.js example的语法)

我还尝试了绝对URL,即agent.get('https://example1.com/path'), but that apparently isn't supported (未捕获的TypeError:无法读取未定义的属性“ address”。)

1 个答案:

答案 0 :(得分:3)

我没来重现错误:Uncaught TypeError: Cannot read property 'address' of undefined

但是,我尝试使用3个node.js服务器,它对我有用(具有绝对路径):

// 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'); });

可能的原因可能是超级代理使用异步方法。它仅在我使用async / await(或.then())时有效。

使用上面的代码,我在具有相同代理的每台服务器上都具有cookie。让我知道我是否理解您的问题以及它是否可以解决您的问题。