【问题标题】:React native set cookie on fetch/axios在 fetch/axios 上反应原生设置的 cookie
【发布时间】:2020-05-06 18:26:30
【问题描述】:

我正在尝试在 fetch 或 axios 上设置 cookie,我已经检查了发布在 github 或 stackoverflow 上的解决方案,但它们现在都没有工作。 我正在使用 Saml 对我的 RN 项目进行身份验证。

所以这里有故事:

第一次登录时,如果用户点击开始按钮,则调用get profile info的api,如果header没有cookie,则返回redirect url和cookie(它是unauth cookie),然后转到webview上的url,用户登录webview后,在webview上调用原始url(get profile api),之后,我会使用react-native-cookies库获取auth cookie,然后将其设置为fetch/axios 的头文件。但它不起作用。

export async function getMyProfile() {
  const cookies = await LocalStorage.getAuthCookies();
    await CookieManager.clearAll(true)
    const url = `${Config.API_URL}/profiles/authme`;
    let options = {
      method: 'GET',
      url: url,
      headers: {
        'Content-Type': 'application/json',
      },
      withCredentials: true
    };
    if (cookies) options.headers.Cookie = cookies.join(';')
    return axios(options)
    .then(res => {
      console.info('res', res);
      return res;
    }).catch(async (err) => {
      if (err.response) {
        if (err.response.status === 401) {
          const location = _.get(err, 'response.headers.location', null);
          const cookie = _.get(err, 'response.headers.set-cookie[0]', null);
          await LocalStorage.saveUnAuthCookie(cookie);
          return { location, cookie, isRedirect: true };
        }
      }
    });
}

【问题讨论】:

  • 你是如何在 react-native 中使用 LocalStorage 的?
  • 登录 webview 后,我会将 cookie 存储在本地存储中。从 LocalStorage 存储/获取正常工作。

标签: react-native axios fetch saml


【解决方案1】:

你可以使用 Axios 拦截器。

  let cookie = null;

  const axiosObj = axios.create({
      baseURL: '',
      headers: {
        'Content-Type': 'application/json',
      },
      responseType: 'json',
      withCredentials: true, // enable use of cookies outside web browser
    });

    // this will check if cookies are there for every request and send request
    axiosObj.interceptors.request.use(async config => {
      cookie = await AsyncStorage.getItem('cookie');
      if (cookie) {
        config.headers.Cookie = cookie;
      }
      return config;
    });

【讨论】:

  • 我天真地尝试过,但似乎 React Native 中的 cookie 管理并不是那么简单。
猜你喜欢
  • 1970-01-01
  • 2021-12-31
  • 2020-11-16
  • 2019-07-16
  • 1970-01-01
  • 2016-05-11
  • 2018-09-01
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多