首页 > 解决方案 > 如何强制 axios 不在 GET 请求中缓存

问题描述

我在我的 React-Native 应用程序中使用 axios

首先,配置标题

function configHeaders()
{
    // I tested all these below 3 lines , no on worked
    axios.defaults.headers.common["Pragma"] = "no-cache";
    axios.defaults.headers.common["Cache-Control"] = "no-cache";
    axios.defaults.headers.common["Cache-Control"] = "no-store";
}

以下请求返回的数据是旧数据,而不是我数据库中的当前数据

exports.getInfo = async function ()
{
    configHeaders();
    return await cachios.get(URL + '/user/info').then(data => {
        return { success : true , data : data.data.data.user };
    }).catch(err => {
        return { success : false , message : err.response.data.message };
    });
}

标签: javascriptnode.jsajaxreact-nativeaxios

解决方案


您可以尝试在 URL 中添加缓存破坏器 - 强制将每个请求视为新请求:

const cacheBuster = (url) => `${url}?cb=${Date.now()}`;
exports.getInfo = async function ()
{
    configHeaders();
    return await cachios.get(cacheBuster(URL + '/user/info')).then(data => {
        return { success : true , data : data.data.data.user };
    }).catch(err => {
        return { success : false , message : err.response.data.message };
    });
}

推荐阅读