[英]NUXT-PWA to cache the POST request
我正在使用NUXT-PWA
缓存我的数据,但我有一个依赖于要构建的POST
请求的页面,我需要缓存响应JSON
但我收到以下错误:
Uncaught (in promise) attempt-to-cache-non-get-request: Unable to cache '/api/hotel/order/get-voucher' because it is a 'POST' request and only 'GET' requests can be cached.
我在workbox-range-request.js
中使用的代码是这样的:
workbox.routing.registerRoute(
new RegExp('/api/(.*)'),
new workbox.strategies.CacheFirst({
cacheName: 'apiCache',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 100,
maxAgeSeconds: 7 * 24 * 60 * 60, // 7 Days
}),
],
}),
'POST'
);
和我的nuxt.config.js
:
workbox: {
dev:true,
cachingExtensions: '@/plugins/workbox-range-request.js',
runtimeCaching: [
{
urlPattern: 'https://www.google-analytics.com/.*',
handler: 'StaleWhileRevalidate',
method: 'GET',
strategyOptions: { cacheableResponse: { statuses: [0, 200] } }
}
]
},
在文档中说它支持POST
但在控制台中我得到了错误并且在我的cacheStore
中我没有得到任何数据。
缓存存储 API 可防止您在保存条目时使用POST
请求作为键。 这部分是因为POST
请求“传统上”是实际发送到服务器以对远程 state 进行更改的东西,并且在那个 model 中,通过本地缓存的响应来实现这一点,而不会到达服务器感觉。
但是...假设您在发送POST
请求后确实在响应正文中获得了有意义的数据,并且您希望使用缓存存储 API 保存该响应正文,使用具有可能不同的 URL 作为缓存键的GET
请求.
您可以通过cacheKeyWillBeUsed
自定义插件使用 Workbox 来做到这一点:
const savePostResponsePlugin = {
cacheKeyWillBeUsed: async ({request, mode}) => {
if (mode === 'write') {
// Use the same URL as `POST` request as the cache key.
// Alternatively, use a different URL.
return request.url;
}
},
};
workbox.routing.registerRoute(
new RegExp('/api/(.*)'),
new workbox.strategies.CacheFirst({
cacheName: 'apiCache',
plugins: [
// Add the custom plugin to your strategy.
savePostResponsePlugin,
new workbox.expiration.Plugin({...}),
],
}),
'POST'
);
我不建议这样做,除非您特别确定要将POST
响应正文保存在缓存中是有充分理由的。
如果您只是在寻找一种在初始尝试因离线而失败时重新发送POST
请求的方法,我建议您改用workbox-background-sync
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.