Mac Ventura 13.2.1的Safari搭配Pug无法加载CSS及图标求助
Mac(Ventura 13.2.1)系统下Safari搭配Pug模板无法加载CSS及网站图标
请帮忙解决以下问题:
错误信息
Unsafe attempt to load URL https://localhost:3000/img/icons.svg from origin http://localhost:3000. Domains, protocols and ports must match.Failed to load resource: An SSL error has occurred and a secure connection to the server cannot be made.
开发者工具网络面板信息
Summary URL: https://localhost:3000/css/style.css Status: — Source: — Initiator: localhost:1
初步判断
该问题与SSL协议不匹配相关。
文件位置
root>public>css>style.css
代码示例
Express静态资源配置
app.use(express.static(path.join(__dirname, 'public')));
Pug模板代码
doctype html html(lang='en') head link(rel='stylesheet' href='/css/style.css' type='text/css') link(rel='shortcut icon' type='image/png' href='/img/favicon.png')
已尝试操作
已搜索相关问题并测试多种方案,均未解决问题,但切换至Chrome浏览器一切正常。尝试过的方案包括:
- 配置Content-Security-Policy:
res.set( 'Content-Security-Policy', "default-src 'self';font-src fonts.gstatic.com;style-src 'self' 'unsafe-inline' fonts.googleapis.com" ); - 在Pug模板内直接引入CSS:
style include css/style.css
解决方案
1. 统一页面与资源的访问协议
错误核心是页面通过http://localhost:3000加载,而资源请求使用https://localhost:3000,协议不匹配触发Safari的安全拦截:
- 使用HTTP开发:检查代码中是否存在强制资源跳转HTTPS的逻辑(如中间件、模板重写规则),确保资源链接与页面协议一致。
- 使用HTTPS开发:为Express配置SSL证书,确保整个服务走HTTPS:
生成证书后,双击const https = require('https'); const fs = require('fs'); // 需提前生成本地SSL证书 const sslOptions = { key: fs.readFileSync('./localhost-key.pem'), cert: fs.readFileSync('./localhost.pem') }; https.createServer(sslOptions, app).listen(3000);.pem文件导入钥匙串访问,将其设置为始终信任,解决SSL证书不被Safari认可的问题。
2. 优化资源链接写法
将Pug模板中的资源链接改为自动匹配页面协议的形式:
link(rel='stylesheet' href='//localhost:3000/css/style.css' type='text/css') link(rel='shortcut icon' type='image/png' href='//localhost:3000/img/favicon.png')
这种写法会自动沿用当前页面的HTTP/HTTPS协议,避免协议不一致问题。
3. 关闭Safari的HTTPS强制功能
打开Safari偏好设置 → 隐私,取消勾选「强制所有网站使用HTTPS」(若该选项存在),防止Safari强制将HTTP资源请求转为HTTPS。
4. 清除Safari缓存与网站数据
打开Safari偏好设置 → 隐私 → 管理网站数据,删除localhost相关的缓存记录,重启Safari后重试。
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

