javascript - 使用 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 示例的语法)
我也尝试过绝对 URL,即agent.get('https://example1.com/path'), but that apparently isn't supported (
Uncaught TypeError: Cannot read property 'address' of undefined`)。
解决方案
我没有来重现错误: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'); });
可能的原因可能是 superagent 使用了异步方法。只有当我使用异步/等待(或.then())时,它才有效。
使用上面的代码,我在每台服务器上都有相同代理的 cookie。让我知道我是否很好地理解了您的问题以及它是否解决了您的问题。
推荐阅读
- list - 递归在 Haskell 中是如何工作的?- 示例合并功能
- python - 如何使用ifelse定义的函数在python中找到非线性方程的解
- google-sheets - 我需要帮助制作一个脚本来为单元格中的代码字着色
- python - 如果字符串太长,则无法从功率计获得响应
- rust - 如果 strong_count 为 1 且 weak_count 为 0,则包含 `Rc` 的`Send` 结构是否安全?
- c# - 无法使用 C# getAsync url 调用打印 JSON 响应
- python - 在推理期间从自定义 Tensorflow/Keras 层中提取中间变量 (TF 2.0)
- excel - 数据验证下拉列表 - 不显示第一个值?
- selenium - Serenity BDD 报告生成
- python - 多参数化标记