在React Native中使用POST方法提交表单失败

时间:2019-06-13 11:22:25

标签: react-native cookies

我正在尝试使用Cookie进行身份验证。我当前的react native解决方案适用于android方面,但不适用于ios。

问题: 我有一个Web视图,它以POST方法将表单提交到url。提交表单后,它将在响应中设置一些cookie,以便用户浏览器了解会话详细信息等。 设置cookie后,我们使用CookieManager in react native检查cookie,然后使用设置的cookie呈现特定的Web视图。但是,我们不提取然后注入cookie,而只是使用已设置的cookie渲染页面。

代码

import RCTNetworking from 'RCTNetworking';
import CookieManager from 'react-native-cookies';

async function getLoginURL() {
  return fetch(`https://www.example.com/login`, {
    credentials: 'same-origin',
  });
}

export function clearCookies() {
  RCTNetworking.clearCookies(() => {});
}

export async function isLoggedIn() {
  const cookies = await CookieManager.get('https://www.example.com');
  return cookies && cookies.SESSION_STATE;
}

export async function login(username, password) {
  
  try {
    clearCookies()
    const loginURL = await getLoginURL();
    const formData = new URLSearchParams();
    formData.append('username', usernamr);
    formData.append('password', password);
    formData.append('method', 'ExtraParameterForBacked');

    const resAuth = await fetch(loginURL, {
      method: 'POST',
      body: formData.toString(),
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    if (!resAuth.ok) {
      return { ok: false, error: 'Could not fetch the authentication form' };
    }
    
    const cookies = await CookieManager.get('https://www.example.com');
    console.log(cookies) // Here I expect that when I hit the domain the cookies are set.
    // Even if I try to hit the login page again it does not have the set cookies
    // This method works in android but in ios, it does not seem to work at all
    
    // Do some other checking with resAuth variable

    return { ok: true };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}
我到目前为止所做的事情: 我在两个请求中都更改了使用credentials: 'include'的请求,但仍然无法正常工作。问题是代码可在android上运行,但不适用于ios。另外请注意,提交表单也使用重定向,我认为重定向会自动进行。不知道,我在ios方面缺少什么。当我检查页面时,它仍然在登录页面上,它无法对我进行身份验证,因此我认为表单提交有问题。感谢您的帮助。

0 个答案:

没有答案