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

如何在Tauri后端为tokio-tungstenite的WebSocket客户端设置Origin头

在Tauri后端为tokio-tungstenite的WebSocket客户端添加Origin头

在JavaScript中可以直接通过WebSocket构造函数的配置项设置Origin头,但使用tokio-tungstenite的connect_async方法时,默认不会携带自定义Origin头,需要通过ClientBuilder来手动配置。

修改后的实现代码

use tungstenite::client::ClientBuilder;
use url::Url;

// 替换为你的业务代码上下文
let url = Url::parse("wss://server.example.com").expect("Can't connect to URL");
let (mut ws_remote, _) = ClientBuilder::new()
    .header("Origin", "https://example.com")
    .connect_async(url)
    .await?;

说明

  • ClientBuilder是tokio-tungstenite提供的客户端构造器,支持自定义WebSocket握手阶段的HTTP请求头。
  • 通过header方法传入Origin字段和对应的值,就能在握手请求中带上指定的Origin头,和JavaScript中的配置效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:36:23