我正在使用 request 来请求包含以下代码的页面:
request(url, { json: true }, (err, res, body) => {
if (err) {
return null
} else {
console.log("res", res.headers["cache-control"]);
}
})
我可以通过这种方式获取缓存控制 header 。但是如何获取缓存控制 header 中的 max-age
值,例如 cache-control: public, max-age=20140, Must-revalidate, no-transform
?有没有速记或者我必须进行字符串操作?
最佳答案
没有简写 - header 只是键/值对,JS 中没有标准库来解析结构化 header 值。
您可以使用正则表达式来提取数字:
const headers = {
'cache-control': 'public, max-age=20140, must-revalidate, no-transform'
}
const matches = headers['cache-control'].match(/max-age=(\d+)/)
const maxAge = matches ? parseInt(matches[1], 10) : -1
console.log(maxAge)
关于node.js - 如何使用 Nodejs 中的请求从缓存控制 header 获取 max-age 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60154782/