Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用reactn时标记的换行提取函数_Reactjs_Jwt_Reactn - Fatal编程技术网

Reactjs 使用reactn时标记的换行提取函数

Reactjs 使用reactn时标记的换行提取函数,reactjs,jwt,reactn,Reactjs,Jwt,Reactn,我正在使用reactn存储访问和刷新登录令牌。通常,要执行API调用,我会执行以下操作 fetch('/api/options/1/', { method: 'PUT', credentials: 'same-origin', body: JSON.stringify(state), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${a

我正在使用reactn存储访问和刷新登录令牌。通常,要执行API调用,我会执行以下操作

fetch('/api/options/1/', {
    method: 'PUT',
    credentials: 'same-origin',
    body: JSON.stringify(state),
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${auth.access.token}`,
    },
})
但由于访问令牌很快过期,因此很容易失败。我想做的是将fetch函数包装在一个类似“callAPI(url,options)”的函数中,该函数将执行以下操作:

  • 检查访问令牌是否过期(
    global.auth.access.exp
    variable)。如果过期,则首先调用
    /api/auth/token/refresh
    传递刷新令牌以获取新的访问令牌
  • 发送
    fetch
    ,并自动添加
    Authorization
    标题
  • 回报承诺

  • 当身份验证信息存储在
    reatn
    全局状态中,以便在任何组件中我都可以导入函数
    callAPI
    并执行API调用时,最好的方法是什么?

    考虑到您使用的是异步/等待语法,您可以使用以下方法执行此操作:

    const fetchWrapper = async (URI, options) => {
        const auth = await fetch('/api/auth/token/refresh');
        const newOptions = {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${auth.access.token}`,
            },
        }
        const res = await fetch(URI, newOptions);
        return res;
    }
    
    如果您未使用async/Wait,则可以使用以下命令:

    const fetchWrapper = (URI, options) => {
        const promise = new Promise((resolve, reject) => {
            fetch('/api/auth/token/refresh').then((auth) => {
                const newOptions = {
                    ...options,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${auth.access.token}`,
                    },
                }
                fetch(URI, newOptions).then(res => {
                    resolve(res);
                }).catch((err) => {
                    reject(err);
                });
            }).catch((err) => {
                reject(err);
            });
        })
    
        return promise;
    }