Fetch API不捕获重定向:React Native项目中的'manual'

z9gpfhce  于 2023-08-07  发布在  React
关注(0)|答案(2)|浏览(101)

我在React Native项目中使用Fetch API。我向服务器发送HTTP POST请求,它需要用户名和密码。如果登录成功,服务器在登录页面设置会话cookie,然后重定向到另一个名为博客的网页。Fetch API从没有会话cookie的Blog接收响应。所以我需要在重定向发生之前捕获重定向并存储会话cookie。
在文档中,它说redirect: 'manual'应该完成这项工作。不过,我还是从最后一页得到了回应。Fetch API未看到重定向-response.redirected返回undefined。但是请求和响应的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 };

字符串
以下是浏览器中网络活动的屏幕截图:
登录:x1c 0d1x
博客:

以下是日志:

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

0vvn1miw

0vvn1miw1#

目前手动重定向不适用于React-Native上的fetch API(参见此处)

vsnjm48y

vsnjm48y2#

不要使用手册,请尝试使用error
因为使用redirected手动过滤掉重定向会允许伪造重定向,所以在调用fetch()时,应该在init参数中将重定向模式设置为“error”
参考:https://developer.mozilla.org/en-US/docs/Web/API/Response/redirected#disallowing_redirects

相关问题