React Native fetch API cannot disable caching

空扰寡人 提交于 2019-12-22 01:43:43

问题


I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. The server did not receive the request second time. I tried disabling cache with the following code.

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
    };
}

When I call the API through Postman client I see different result(not cached). I tried adding random number as parameter and setting cache control headers, but still returning cached result. Is there is anything else I could try.

Thanks


回答1:


There must be a problem with how are you setting up the headers for fetching request.

Try with following,

You can follow the link for the same in the 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());
};


来源:https://stackoverflow.com/questions/47700360/react-native-fetch-api-cannot-disable-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!