You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何在API调用中正确传递登录Token?

解决React Native中API调用的Token传递问题

你的代码存在两个核心问题,导致Token无法正确传递到API请求中:

1. 异步函数调用未使用await

retrieveToken是异步函数,直接调用会返回Promise对象而非实际的Token字符串。这会导致Authorization头被拼接成Token [object Promise],触发API验证失败,进而引发报错。

2. AsyncStorage键名大小写不匹配

登录时你用"Token"(首字母大写)作为键存储Token,但retrieveToken中用"token"(全小写)读取,导致无法获取到存储的Token,最终返回null。


修正后的代码

修正fetchCategoryData函数(添加await)

export const fetchCategoryData = async () => {
    try {
        // 用await获取真实的Token值,而非Promise对象
        const token = await retrieveToken();
        if (token) {
            console.log(token);
            const response = await fetch("http://192.168.1.65:8000/api/categories/main_groups/", {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Token ${token}`,
                },
            });
            return await response.json();
        } else {
            throw new Error("未获取到有效Token");
        }
    } catch (error) {
        console.log(error);
    }
};

修正loginRequest函数(统一键名)

export const loginRequest = async (email, password) => {
    try {
        const response = await fetch("http://192.168.1.65:8000/api/user/token/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email: email,
                password: password,
            }),
        });

        const data = await response.json();

        if (response.ok) {
            // 统一键名为"token",和retrieveToken中的读取键一致
            await AsyncStorage.setItem("token", data.token);
            return true;
        } else {
            throw new Error(data.token);
        }
    } catch (error) {
        console.log(error);
        throw new Error("Login failed");
    }
};

内容的提问来源于stack exchange,提问作者mightycode Newton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 18:05:26