You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Fastify响应中移除X-Frame-Options解决跨域PDF加载问题

解决Fastify服务X-Frame-Options跨域iframe加载PDF问题

问题核心是Fastify返回的X-Frame-Options: SAMEORIGIN头阻止了https://confirm.domain.com跨子域名加载PDF,你尝试在路由中直接移除/修改该头无效,大概率是因为这个头在响应发送流程的后期才被添加,需要用Fastify的钩子来处理。

方案1:用onSend钩子移除X-Frame-Options头

onSend钩子会在响应即将发往客户端前触发,这里移除头能确保生效,支持单路由或全局配置:

单路由生效

fastify.get('/your-pdf-path', {
  onSend: (request, reply, payload, done) => {
    reply.removeHeader('X-Frame-Options');
    done();
  }
}, async (request, reply) => {
  // 你的PDF获取/生成逻辑
  const buffer = /* PDF文件buffer */;
  const documentName = /* 文件名 */;

  return reply.code(200)
    .header("Access-Control-Allow-Origin", 'https://confirm.domain.com')
    .header('Content-Disposition', `filename=${documentName}`)
    .type('application/pdf')
    .send(buffer);
});

全局所有路由生效

如果需要所有接口都移除该头,在Fastify实例初始化后、注册路由前添加全局钩子:

fastify.addHook('onSend', (request, reply, payload, done) => {
  reply.removeHeader('X-Frame-Options');
  done();
});

方案2:用Content-Security-Policy替代(推荐)

现代浏览器已弃用X-Frame-Options: ALLOW-FROM,更推荐使用Content-Security-Policy的frame-ancestors指令,兼容性和灵活性更好。在路由中添加该头,同时配合onSend移除原有的X-Frame-Options:

return reply.code(200)
  .header("Access-Control-Allow-Origin", 'https://confirm.domain.com')
  .header('Content-Disposition', `filename=${documentName}`)
  .header('Content-Security-Policy', 'frame-ancestors https://confirm.domain.com')
  .type('application/pdf')
  .send(buffer);

额外排查建议

先确认X-Frame-Options: SAMEORIGIN的来源:

  • 检查是否有其他未留意的插件或全局代码添加了该头
  • Fastify核心默认不会添加这个头,大概率是自定义逻辑或第三方插件导致

内容的提问来源于stack exchange,提问作者Yanick Rochon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:05:30