有人在部署网站后遇到过混合内容问题吗?我构建了一个应用程序,它使用部署到 Azure Web App 的 Fastapi 后端和部署到 vercel 的 NextJs 14 前端。一切都在本地成功运行。 后端和前端通过 CORS 连接。用户可以成功验证。当用户发送问题时(顺便说一句,该应用程序是关于聊天和对象检测的),请求被阻止并且无法到达服务器,就会出现问题。我已经尝试了几种技巧来解决这个问题。我用来找出如何解决这个问题的一些来源是https://web.dev/articles/fixing-mixed-content。
我尝试删除我使用的外部源。我还添加了 CSP,如附加链接中所述:我将其添加到后端,如下所示
@app.middleware("http")
async def add_csp_header(request, call_next):
response = await call_next(request)
# Adding Content-Security-Policy to block or upgrade mixed content
response.headers["Content-Security-Policy"] = "default-src 'self'; upgrade-insecure-requests; block-all-mixed-content"
return response
在前端:
return [
{
// Apply this to all routes
source: '/(.*)', // This applies the header to all routes in your Next.js app
headers: [
{
key: 'Content-Security-Policy',
value: "default-src 'self'; upgrade-insecure-requests; block-all-mixed-content"
}
]
}
];
在 next.config.mjs 中。不幸的是,我仍然遇到同样的错误。 在此输入图片描述 [在此处输入图像描述](https://i.sstatic.net/2CWHCIM6.png).
在您的网站上打开 Chrome DevTools (
F12
),然后转到 Console 选项卡。特别查找有关混合内容的警告或错误。这些错误将指示 HTTPS 页面上正在加载哪些 HTTP 资源。
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-vercel-domain.com"],
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["Content-Type", "Authorization"],
)
尝试此 CSP 规则 -
response.headers["Content-Security-Policy"] = "default-src 'self' https:; upgrade-insecure-requests; block-all-mixed-content"
- 此 cmd 允许来自站点和安全源的内容
日志:
[INFO] Starting application...
[INFO] Connection to FastAPI backend established successfully via HTTPS.
[INFO] WebSocket connection initialized with Azure WebPubSub via wss://your-webpubsub-endpoint.
[INFO] Chat message sent successfully to backend: "Hello!"
[INFO] Object detection request sent to backend.
[INFO] Received response from backend for object detection.
[INFO] CSP: All resources loaded securely.
[INFO] All external resources loaded over HTTPS.
网络表: