React项目嵌入iframe报错:Refused to display in a frame(X-Frame-Options问题)
解决React网站嵌入iframe时X-Frame-Options错误的办法
这个错误的核心原因是你的网站服务器返回的HTTP响应头里X-Frame-Options被设置为sameorigin,浏览器会拒绝非同源页面将其嵌入iframe。以下是不同场景的解决步骤:
1. Create React App(CRA)项目
开发环境
CRA默认开发服务器会设置X-Frame-Options: sameorigin,需要通过自定义配置修改:
- 安装
craco:npm install @craco/craco --save-dev - 项目根目录创建
craco.config.js,添加如下配置:module.exports = { devServer: { headers: { // 替换为允许嵌入你的网站的域名,比如允许https://example.com嵌入 'X-Frame-Options': 'ALLOW-FROM https://example.com' // 若需允许所有域名(不推荐开发外的场景),可改为'ALLOWALL' } } }; - 修改
package.json的启动命令:将"start": "react-scripts start"改为"start": "craco start"
生产环境
生产部署后,需在静态服务器(如Nginx、Apache)的配置里修改响应头:
- Nginx:在站点的
server块中添加:add_header X-Frame-Options "ALLOW-FROM https://example.com"; // 或用CSP指令替代(兼容性更好): // add_header Content-Security-Policy "frame-ancestors 'self' https://example.com;"; - Apache:在
.htaccess或站点配置中添加:Header set X-Frame-Options "ALLOW-FROM https://example.com" // 或CSP指令: // Header set Content-Security-Policy "frame-ancestors 'self' https://example.com;"
2. Vite构建的React项目
开发环境
修改vite.config.js,在server.headers中配置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { headers: { 'X-Frame-Options': 'ALLOW-FROM https://example.com' } } });
生产环境
和CRA生产环境一致,在部署的服务器配置中修改HTTP响应头即可。
3. 带有Express后端的React项目
如果你的项目有Express后端服务,直接在后端添加响应头配置:
const express = require('express'); const app = express(); // 允许指定域名嵌入 app.use((req, res, next) => { res.setHeader('X-Frame-Options', 'ALLOW-FROM https://example.com'); // 或用CSP指令替代: // res.setHeader('Content-Security-Policy', 'frame-ancestors 'self' https://example.com;'); next(); }); // 其他路由和配置... app.listen(3000);
注意事项
- 生产环境尽量避免使用
ALLOWALL或frame-ancestors *,这会带来点击劫持的安全风险,优先指定具体允许的域名。 - 部分现代浏览器对
ALLOW-FROM支持有限,推荐使用CSP的frame-ancestors指令,兼容性更好。
内容的提问来源于stack exchange,提问作者Mani
相关产品推荐
相关产品推荐

