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

Tauri Macbook应用打包为DMG后无法连接本地服务器怎么办?

解决Tauri Mac应用打包DMG后无法连接本地服务器的问题

1. 配置网络权限白名单

Tauri生产环境默认会限制网络请求范围,需在tauri.conf.json的allowlist.network中明确允许访问本地服务器地址:

{
  "tauri": {
    "allowlist": {
      "network": {
        "all": false, // 遵循最小权限原则,关闭全量网络权限
        "request": true,
        "scope": [
          "http://localhost:3456/*",
          "http://127.0.0.1:3456/*" // 同时添加127.0.0.1规避DNS解析异常
        ]
      }
    }
  }
}

2. 调整Content Security Policy(CSP)

生产环境默认CSP会拦截未授权的网络连接,需在tauri.conf.json的security.csp中添加本地服务器源:

{
  "tauri": {
    "security": {
      "csp": "default-src 'self'; connect-src 'self' http://localhost:3456 http://127.0.0.1:3456; script-src 'self'; style-src 'self' 'unsafe-inline';"
    }
  }
}

注意:按需调整CSP规则,避免过度放宽权限引发安全风险。

3. 确认本地服务器绑定地址

确保本地服务器绑定到0.0.0.0而非仅127.0.0.1,部分场景下打包后的WebView可能通过不同回环路径访问;同时验证服务器是否正常运行在3456端口。

4. 检查WebView沙箱设置

若tauri.conf.json中开启了WebView沙箱(默认开启),确认沙箱规则未阻止本地网络请求。必要时可临时关闭沙箱测试(不建议长期关闭,会降低安全性):

{
  "tauri": {
    "windows": [
      {
        "webviewPreferences": {
          "sandbox": false
        }
      }
    ]
  }
}

5. 替代方案:使用Tauri IPC通信

若本地服务器为自主开发,可放弃HTTP请求,改用Tauri的IPC机制直接调用后端逻辑,既规避网络权限问题,又提升通信效率:

  • Rust后端示例:
#[tauri::command]
async fn fetch_local_data() -> Result<String, String> {
    // 直接调用原本地服务器的业务逻辑
    Ok("本地数据内容".into())
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![fetch_local_data])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
  • 前端调用示例:
import { invoke } from '@tauri-apps/api/tauri';

const data = await invoke('fetch_local_data');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:12:18