node.js - 将 JSON 更新到缓存中
问题描述
我目前正在构建一个应用程序,可让您检查 Netflix 上已取消的节目。为了避免为 API 调用付费,我正在运行一个 24 小时增量函数,它将调用的数据存储到 JSON 文件中。JSON 文件然后被发送到前端 (React.js) 并且应该为用户缓存。
我正在尝试的一种解决方法是将获取的服务器数据写入 react/src 文件夹中的 JSON 文件,但我也很难找到任何关于从 React 写入 JSON 文件的好文章。
React 预构建的 serviceworker 已经存储了原始 JSON 文件,但拒绝更新。我找不到任何关于 React serviceworkers 的好文章,只知道如何在 base JS 中操作 serviceworkers。我尝试的所有基础 JS 都失败了,因为 React 需要不同的语法和参数。
后端代码 app.js schedule-node 函数
schedule.scheduleJob('* * */23 * *', function(){
console.log('Daily API call initiated.');
unirest.get("https://unogs-unogs-v1.p.rapidapi.com/aaapi.cgi?q=get:exp:US&t=ns&st=adv&p=1")
.header("X-RapidAPI-Host", "unogs-unogs-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", `${keys.RICHARD_UNOGS_KEY}`)
.end(function (result) {
console.log(result.status, result.headers);
//console.log(result.body) to see all data
let data = JSON.stringify(result.body)
fs.writeFile('./movieData.json', data)
});
})
app.js 向前端发送数据
app.get('/expiring', (req, res) => {
res.json(MovieData)
})
调用 JSON 文件的前端代码组件
componentDidMount() {
let url = "http://localhost:8080/expiring"
fetch(url)
.then(response => response.json())
.then(json => {
console.log(json)
this.setState({
...this.state.movies,
movies: json
})
})
}
serviceWorker.js
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit.......'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https:..........'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
window.addEventListener('fetch', function(event) {
console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
我需要更新缓存的 JSON 文件。我做 npm run build 因为 React 不允许服务工作者,在我的 index.js 中我有 serviceworkers.register。缓存最初已更新,但即使清除后也不会使用新的 JSON 文件进行更新。欢迎任何建议。
编辑:通过将从服务器发送到客户端的 JSON 数据存储在 localhost 密钥中,半解决了我的问题。
解决方案
如果您考虑应用程序架构,您实际需要的是这样的:
- 服务器每 24 小时更新一次 apidata.json
- apidata.json 内容是从某个服务器端点提供的(不管是 /api/apidata.json 还是完全不同的东西,比如 /static/24-hour-data.json)
- 客户端(React 应用程序)随时向服务器请求数据
- 客户端可以选择将来自服务器的数据缓存一段时间或根本不缓存它
这里服务器端和前端逻辑是完全独立的。客户端不需要知道服务器的更新计划,服务器也不需要知道客户端的工作方式。
如果您想在客户端缓存数据以使应用程序更快并可能提供离线功能,您可以使用 Local Storage、IndexedDB 或 Service Worker 在客户端实现缓存。这里的选择并不真正影响架构本身——只是你如何处理缓存。如果你使用例如。SW 中的 Workbox 库您可以轻松地说“/static/apidata.json 中的任何内容都应缓存 24 小时”,它会做到这一点。
为了使整个事情顺利进行,您需要配置 Service Worker 生成,以便 apidata.json 文件不包含在 SW 脚本的预缓存资产中。
推荐阅读
- php - 如何在多维数组中从 WP_Query 数组中获取发布数据?
- codenameone - Google Play 最近的评论通知 - APK 有明显的披露,但披露并不充分
- flutter - 颤振使容器透明,其中包含所有项目
- django - 当 Debug=False 时 Django CountrySelectWidget 不工作
- json - 如何使用 Windows 命令行从这个类似 json 的文件中获取数据?
- python-3.x - 找到标记但类不可见 Python Selenium
- python - 如何在数组数组中找到整个数组的索引?
- python - 为什么在 Python 库和 RIOT OS C 库中编码 CBOR 时存在差异?
- python - Matplotlib 将数组转换为 1 条图表线
- angular - 动态创建打开控件时如何在正确位置打开菜单?