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

如何修复Directus与Next.js草稿模式下的IFrame错误

解决Next.js CSP导致Directus预览嵌入失败的问题

问题分析

你配置了Next.js的CSP规则,其中frame-ancestors包含localhost:8085,但Directus运行在localhost:8085嵌入Next.js(localhost:3000)页面时,仍然触发CSP错误。核心原因可能是CSP规则匹配精度不足、协议缺失或缓存导致新配置未生效。

解决步骤

1. 验证CSP响应头是否正确生效

打开浏览器开发者工具(F12),切换到Network标签,加载被嵌入的Next.js页面,查看响应头中的Content-Security-Policy,确认frame-ancestors确实包含localhost:8085。如果规则未出现,检查next.config.js是否重启生效,或是否有其他插件/配置覆盖了CSP头。

2. 补充协议前缀,确保来源匹配

将frame-ancestors规则修改为包含明确协议的完整来源,避免浏览器因协议不匹配拒绝嵌入:

const ContentSecurityPolicy = `
    default-src 'self';
    script-src 'self' 'unsafe-eval' 'unsafe-inline';
    child-src 'self';
    style-src 'self' 'unsafe-inline';
    img-src * blob: data:;
    media-src 'none';
    connect-src *;
    font-src 'self' data:;
    frame-src 'self' http://localhost:8085 https://localhost:8085;
    frame-ancestors 'self' http://localhost:8085 https://localhost:8085;
`;

3. 清除浏览器缓存

浏览器会缓存HTTP响应头,可能导致新的CSP规则未生效。按Ctrl+Shift+R(Windows)或Cmd+Shift+R(Mac)强制刷新页面,或直接清空浏览器缓存后重试。

4. 针对预览页面单独放宽CSP(可选)

如果仅预览页面需要被Directus嵌入,可对预览路径单独配置宽松的CSP,避免全局降低安全等级:

headers() {
    return [
        {
            source: '/(.*)',
            headers: securityHeaders,
        },
        {
            // 替换为你的实际预览路径,比如/api/preview或/preview
            source: '/api/preview|/preview',
            headers: [
                ...securityHeaders,
                {
                    key: 'Content-Security-Policy',
                    value: ContentSecurityPolicy.replace(
                        /frame-ancestors .*?;/,
                        'frame-ancestors \'self\' http://localhost:8085 https://localhost:8085;'
                    ),
                },
            ],
        },
    ];
},

5. 检查Directus预览配置

确认Directus中设置的预览URL与Next.js的预览地址完全一致,包括协议(http/https)、域名和端口,避免因URL拼写错误导致CSP校验失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:35:00