【问题标题】:Expose Content-Disposition header on NextJS在 NextJS 上公开 Content-Disposition 标头
【发布时间】:2022-03-09 04:47:05
【问题描述】:

我正在尝试使用 axios 在来自外部 API 的响应中获取 Content-Disposition 标头。

尽管 Chrome DevTools 网络响应中存在标头,但我似乎无法从服务器访问该特定标头。

我发现这个 article 谈论通过 Access-Control-Expose-Headers 公开 Content-Disposition 标头,但我不太确定如何在 Nextjs 中实现它。

我尝试按照 Nextjs 文档页面中关于security headers 的说明编辑next.config.js 文件,如下所示,但没有运气

/** @type {import('next').NextConfig} */
module.exports = {
  reactStrictMode: true,
  async headers() {
    // to allow specific headers to appear in requests
    // https://nextjs.org/docs/advanced-features/security-headers
    const securityHeaders = [
      // important
      { key: "Access-Control-Expose-Headers", value: "Content-Disposition" },
    ]
    return [
      {
        source: '/:path*', // req path
        headers: securityHeaders
      }
    ]
  }
}

这是我使用 axios 进行的 API 调用:

// lib/utils.js

export async function downloadFile(collectionName: string, documentId: string) {
  const res = await axios.get(
    `https://api.myapiendpoint.com/file/${collectionName}/${documentId}`
  );
  console.log(res.headers);
}

Chrome DevTools 日志:

console.log 输出:

// these are the only headers I receive
{
    "content-length": "195687",
    "content-type": "text/csv; charset=utf-8",
    "last-modified": "Thu, 10 Feb 2022 16:00:05 GMT"
}

【问题讨论】:

  • “我似乎无法从服务器访问该特定标头” - 你如何从服务器访问它?
  • 嗨@juliomalves。刚刚用我尝试使用 axios 所做的事情以及我从服务器收到的响应更新了我的问题。我对这个主题不是很实际,如果还有什么我可以帮助的,请告诉我:)

标签: reactjs axios request next.js


【解决方案1】:

我有 99.99% 的把握,我相信这很可能是后端问题。当我需要实现下载 pdf/csv 逻辑(带有文件名)时,我遇到了完全相同的问题,该逻辑需要从响应中访问 c​​ontent-disposition 标头。

现在,无论我尝试什么,我总是可以在开发工具和邮递员中看到该标题,但在我的控制台中却看不到。经过大量的努力并说服了我的后端团队成员,结果发现后端并没有暴露它。

检查你的后端(无论它使用什么技术),问题就在那里;)

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 2018-10-30
    • 2017-10-29
    • 2010-11-03
    相关资源
    最近更新 更多