node.js - 如何使用 Nodejs 中的请求从缓存控制 header 获取​​ max-age 值?

标签 node.js http request

我正在使用 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/

相关文章:

python - Django - 使用外部脚本从 url 下载图像并将其插入 imageField

java - 如何从 Spring Boot Controller 返回超链接?

node.js - NPM : how to source ./node_modules/.bin 文件夹?

node.js - 如何修复 Typescript 编译错误 ts2345 "Type ' 响应'丢失......来自类型 'Response' : redirected, 预告片,formData!”

node.js - 如何创建只能被前端访问的私有(private)api?

python - 如何使用 Python 将多部分 PDF 请求发送到 OneNote

ios - NSURLConnection - didReceiveData 没有被调用 - iOS 和 ARC

java - 在 Android 上更改 HTTP 基本身份验证的加密

elasticsearch - 从 ElasticSearch 中按域获取 10 个最佳结果

node.js - 任务似乎已注册但无法运行?