React Native中Fetch API设置redirect:'manual'无法捕获重定向
我在React Native项目里使用Fetch API发送携带用户名和密码的HTTP POST登录请求。登录成功后,服务器会在Login页面设置会话Cookie,随后重定向至Blog页面。但Fetch API接收到的是Blog页面的响应,其中并不包含会话Cookie,因此我需要在重定向发生前捕获它并存储会话Cookie。
根据文档说明,设置redirect: 'manual'应该可以实现该功能,但我仍获取到最终页面的响应,Fetch API未识别到重定向——response.redirected返回undefined,不过请求URL与响应URL确实不同。请问可能是什么原因导致的?
相关代码
const url = 'url of a website ( cannot show it to you )'; // login request const login = (profileName, password) => { const details = { benutzername: profileName, passwort: password, }; const formBody = Object.keys(details) .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`) .join('&'); console.log(`formBody to be sent: ${formBody}`); fetch(url, { method: 'POST', headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Content-Type': 'application/x-www-form-urlencoded', }, body: formBody, redirect: 'manual', }) .then((response) => { console.log('! response type !'); console.log(response.type); console.log('! is redirected !'); console.log(response.redirected); console.log('! response console log !'); console.log(response.url); console.log('! response status console log !'); console.log(response.status); return response.headers; }) .then((headers) => { console.log('! headers for each !'); headers.forEach((value, key) => { console.log(`${key} ==> ${value}`); }); return headers; }) .catch((error) => console.log(`error: ${error}`)); }; export { login };
浏览器网络活动截图
- Login页面网络活动:

- Blog页面网络活动:

日志信息
LOG ! response type ! LOG default LOG ! is redirected ! LOG undefined LOG ! response console log ! LOG https://.../Blog.xhtml?faces-redirect=true&dswid=-8890 LOG ! response status console log ! LOG 200 LOG ! headers for each ! LOG cache-control ==> no-cache, no-store, must-revalidate LOG content-encoding ==> gzip LOG content-type ==> text/html;charset=UTF-8 LOG date ==> Sun, 23 Jul 2023 14:54:59 GMT LOG expires ==> 0 LOG pragma ==> no-cache LOG server ==> Apache LOG set-cookie ==> dsrwid--8890=-8890; path=/; secure; Max-Age=60; Expires=Sun, 23-Jul-2023 14:55:59 GMT; SameSite=None LOG vary ==> Accept-Encoding
内容的提问来源于stack exchange,提问作者user22272238
相关产品推荐
相关产品推荐

