首页 > 解决方案 > 使用 cookie 反应本机登录

问题描述

我正在尝试创建一个小应用程序,并且我正在通过返回 cookie 的 api 登录。我在我的应用程序中查找和处理 cookie 时遇到问题。有什么建议么?

我的获取方法:

async login() {
    try { 
        let response = await fetch('http://192.168.168.114:8090/Cam/LoginOut/role', {
            credentials: 'include',
            method: 'POST',
            headers: { 
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              role: "CamTherapist",
              username: this.state.username,
              password: this.state.password
            })
        });
        let res = await response.text();
        if(response.status >= 200 && response.status < 300) {
            let accessToken = res;
            console.log("res is + " + res);
            this.props.navigation.navigate('Idag');
        } else {
            this.props.navigation.navigate('Idag');
            let errors = res;
            console.log(response.status + " fejl, Jeg er næsten inde");
            throw errors;
        }

    }   catch (errors) {
        console.log('There has been a problem with your fetch operation: ');
        // ADD THROW ERRORS EVENTUALLY
    }
}

标签: react-nativecookiesfetch

解决方案


Cookie 通常作为名为Set-Cookie. 您可以使用response.headers.

因此,为了本地化您的 cookie:

let headers = response.headers
let newCookie = headers['Set-Cookie']

请注意,Set-Cookie标头包含 cookie 键、其值以及一些进一步的信息,例如到期日期。您将需要解析字符串以检测特定信息。

需要注意的是,在 React Native 中,fetch 应该支持开箱即用的 cookie,因此您应该已经能够在以下请求中使用 cookie,而无需任何进一步的代码


推荐阅读