【问题标题】:React Native fetch API cannot disable cachingReact Native fetch API 无法禁用缓存
【发布时间】:2018-05-21 20:57:24
【问题描述】:

我正在使用与 redux 集成的 react native expo 构建 android 应用程序。使用 fetch 方法调用 API,但始终显示缓存的结果。服务器第二次没有收到请求。我尝试使用以下代码禁用缓存。

export const mymails = (token) => {
    return fetch(
        API_URL+'?random_number='+ new Date().getTime(), {
        method: 'GET',
        headers: getHeaders(token)
    })  
    .then(response => response.json());
};

getHeaders = (token) => {
    return {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Token token='+token,
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': 0
    };
}

当我通过 Postman 客户端调用 API 时,我看到了不同的结果(未缓存)。我尝试添加随机数作为参数并设置缓存控制标头,但仍返回缓存结果。还有什么我可以尝试的。

谢谢

【问题讨论】:

  • 有趣。 AFAIK,fetch api不会自动缓存任何东西。也许缓存发生在 API 端?你愿意分享 api 端点以便我使用它吗?
  • 我认为' Cache-Control': 'no-cache' 必须有效。能否请您分享 API 端点以便我们检查问题
  • 对不起,这是服务器中的错误。我调用了一个不同的函数,而不是我正在编辑的函数。啊。愚蠢的我。
  • 你可以删除这个问题

标签: react-native react-redux fetch-api


【解决方案1】:

你是如何设置获取请求的标头的,一定有问题。

尝试跟随,

您可以点击Official Fetch API中的相同链接

const mymails = (token) => {

    var myHeaders = new Headers();
    myHeaders.set('Accept', 'application/json');
    myHeaders.set('Content-Type', 'application/json');
    myHeaders.set('Authorization', 'Token token=' + String(token));
    myHeaders.set('Cache-Control', 'no-cache');
    myHeaders.set('Pragma', 'no-cache');
    myHeaders.set('Expires', '0');

    return fetch(
        API_URL + '?random_number=' + new Date().getTime(), {
            method: 'GET',
            headers: myHeaders
        })
        .then(response => response.json());
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-19
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多