Nodejs superagent 的坑:各位是如何处理 redirect 的?
Nodejs superagent 的坑:各位是如何处理 redirect 的?
我在爬一个网页,模拟登录,POST 后得到一个临时 cookie,再用这个临时 cookie 去访问重定向的网址,这个网址返回的 cookie 才是真正需要的 cookie.
但 superagent 默认自动 redirect 时,不会带上临时 cookie,导致登陆失败. 如果用它的 redirects(0),来禁止重定向,又会抛出异常,程序又无法得到临时 cookie.
有大佬知道怎么解决这个问题吗?
4 回复
superagent.agent()无效吗?
不是很懂你的意思
要不你直接用 .agent()
自动维护 cookie 试试
理论上手动维护也是可行的
菜鸟感谢你们~
在Node.js中使用superagent处理重定向(redirect)时,确实可能会遇到一些坑。默认情况下,superagent会自动处理HTTP 3xx的重定向响应,但有时候你可能需要自定义这种行为。
以下是一些处理superagent重定向的常见方法:
-
禁用自动重定向: 如果你想完全控制重定向行为,可以禁用自动重定向,并手动处理。
const superagent = require('superagent'); superagent.get('http://example.com') .redirects(0) // 禁用自动重定向 .end((err, res) => { if (res && res.statusCode === 302) { // 手动处理重定向逻辑 const location = res.headers.location; console.log('Redirecting to:', location); // 发起新的请求到重定向地址 superagent.get(location).end((err, res) => { console.log(res.body); }); } });
-
限制重定向次数: 你可以限制重定向的最大次数,防止无限重定向。
superagent.get('http://example.com') .redirects(5) // 最多重定向5次 .end((err, res) => { if (err) { console.error('Error:', err); } else { console.log('Final response:', res.body); } });
通过上述方法,你可以更好地控制superagent在处理HTTP重定向时的行为,从而避免一些潜在的坑。