Skip to content

401 unauthorized 情况下想刷新 token,再发起相同的请求,这样是否好? #17

@wyudong

Description

@wyudong

我想改写 utils/fetch.js,让网路请求返回 401(unauthorized) 时,也就是用户 token 过期时,自动请求刷新 token,然后以新 token 发起上一次的请求。这样做是为了即延续 token 的有效性,又不让用户重新登录。但我不清楚这样做是否可行?刷新 token 之后发起相同的请求,怎样写不至于显得啰嗦?希望能得到指点,谢谢。

export default function _fetch(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            baseURL: process.env.BASE_API,
            headers: {
                'X-Ivanka-Token': store.getters.token
            }
        });
        instance(options).then(response => {
            const res = response.data;

            // 401 unauthorized
            if (res.code === 401) {
                refreshToken().then(response => {
                    // 得到新 token
                    const token = response.data.token;

                    //
                    // 接下去如何以新 token 发起上一次的请求?
                    //
                }).catch(error => {
                    reject(error);
                })
                reject(res);
            }

            // everything's fine
            resolve(res);
        }).catch(error => {
            reject(error);
        });
    });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions