首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GET in angular js的ETag -我需要检查服务器端吗?

GET in angular js的ETag -我需要检查服务器端吗?
EN

Stack Overflow用户
提问于 2015-09-15 23:56:50
回答 3查看 2.7K关注 0票数 1

我正在尝试在angular JS中为GET请求实现etag,到目前为止,我已经看到了https://github.com/forforf/angular-etag https://www.npmjs.com/package/angular-http-etag和restangular(一个复杂但很好的工具)。他们都说它提供了对GET请求的内置支持,我认为这意味着我不需要在服务器端(它是在c#.NET中)编写任何代码。

我的假设是正确的吗,或者我必须使用CacheCow或其他东西来查找报头中的ETAG并发送304响应。

这只是一个背景,我不得不使用ETAG而不是缓存(角度),以便从服务器获取最新数据。

EN

回答 3

Stack Overflow用户

发布于 2019-04-11 02:01:37

我想要一个基于$http拦截器的解决方案,因为我需要它与$http的所有用户一起工作,而且我不能像angular-http-etag那样使用$http装饰器,因为例如来自Angular Translate的$translateProvider.useStaticFilesLoader使用$http,我希望这些调用也被缓存。

下面的解决方案是用Typescript编写的,它将从本地存储中存储/检索缓存,并且只保留最新的25个缓存项目。

代码语言:javascript
复制
interface CacheObject {
    data: any;
    etag: string;
    index: number;
}

appModule.config(['$httpProvider', ($httpProvider) => {
    const cacheKey = 'add_your_unique_custom_localstorage_key_here';
    const cacheSize = 25;
    let index = 0;
    let cache: {[key: string]: CacheObject};

    const cacheString = localStorage.getItem(cacheKey);

    if (cacheString == null) {
        cache = Object.create(null);
    } else {
        cache = JSON.parse(cacheString);
        let cacheEntries = Object.entries(cache);

        for (const entry of cacheEntries) {
            // Find largest index
            const entryIndex = entry[1].index;
            if (entryIndex > index) {
                index = entryIndex;
            }
        }
        if (index > Number.MAX_SAFE_INTEGER) {
            // Reset cache if index gets larger than max safe int
            // This is kind of a theoretical problem
            cache = Object.create(null);
            cacheEntries = [];
            index = 0;
        }

        if (cacheEntries.length > cacheSize) {
            // Clean up cache once in a while. Only keep the 25 newest items
            const sortedCacheEntries = cacheEntries.sort((a, b) => {
                return b[1].index - a[1].index;
            });
            sortedCacheEntries.length = cacheSize;
            cache = sortedCacheEntries.reduce(
                (accum, [k, v]) => {
                    accum[k] = v;
                    return accum;
                },
                Object.create(null),
            );
        }
    }

    $httpProvider.interceptors.push(['$q', ($q: ng.IQService) => {
        return {
            response: (response) => {
                const headers = response.headers();
                if (response.status === 200 && headers.etag) {
                    const cacheObject = {
                        data: response.data,
                        etag: headers.etag,
                        index: index++,
                    };
                    cache[response.config.url] = cacheObject;
                    localStorage.setItem(cacheKey, JSON.stringify(cache));
                }
                return response;
            },
            responseError: (response) => {
                if (response.status === 304) {
                    const cacheObject = cache[response.config.url];
                    if (cacheObject != null) {
                        const data = cacheObject.data;
                        const dataString = JSON.stringify(data);
                        const clonedData = JSON.parse(dataString);
                        response.data = clonedData;
                        // Will only recover if we set status to 200
                        response.status = 200;
                        return $q.resolve(response);
                    }
                }
                return $q.reject(response);
            },
            request: (config) => {
                const cacheObject = cache[config.url];
                if (cacheObject != null) {
                    config.headers['If-None-Match'] = cacheObject.etag;
                }
                return config;
            },
        };
    }]);
}]);
票数 1
EN

Stack Overflow用户

发布于 2016-08-26 05:09:11

我是angular-http-etag的作者,所以我只能直接介绍该模块的功能。它装饰了Angular的$http服务,允许您指定要缓存的请求。下面是我在readme.md中提供的用法示例:

代码语言:javascript
复制
angular
  .module('myApp', [
    'http-etag'
  ])
  .config(function (httpEtagProvider) {
    httpEtagProvider
      .defineCache('persistentCache', {
        cacheService: 'localStorage'
      })
  })

  .controller('MyCtrl', function ($http) {
    var self = this

    $http
      .get('/my_data.json', {
        etagCache: 'persistentCache'
      })
      .success(function (data, status, headers, config, itemCache) {
        // Modify the data from the server
        data._fullName = data.first_name + ' ' + data.last_name
        // Update the cache with the modified data
        itemCache.set(data)
        // Assign to controller property
        self.fullName = data._fullName
      })
      // Synchronous method called if request was previously cached
      .cached(function (data, status, headers, config, itemCache) {
        self.fullName = data._fullName
      })
      .error(function (data, status) {
        // 304: 'Not Modified'--Etag matched, cached data is fresh
        if (status != 304) alert('Request error')
      })
  })

服务器端唯一需要做的就是确保服务器正在发送ETag响应头。你可以在这里找到关于如何在Chrome中检查响应头的信息:https://developers.google.com/web/tools/chrome-devtools/profile/network-performance/resource-loading#view-details-for-a-single-resource

票数 0
EN

Stack Overflow用户

发布于 2017-02-22 17:08:54

好吧,对于某些服务器必须支持发布ETags,而ASP.NET MVC或Web默认不支持。您必须在服务器上使用某种形式的输出缓存。

其中一个这样的项目是Filip Woj的CacheOutput

https://github.com/filipw/Strathweb.CacheOutput

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32590555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档