13 HTTP Client

原文链接: https://tauri.app/plugin/http-client/

使用 http 插件发起 HTTP 请求。

支持的平台

平台支持程度说明
Windows完整支持
Linux完整支持
macOS完整支持
Android完整支持
iOS完整支持

设置

自动

使用你的项目包管理器添加依赖:

1
npm run tauri add http
1
yarn run tauri add http
1
pnpm tauri add http
1
deno task tauri add http
1
bun tauri add http
1
cargo tauri add http

手动

  1. 在 src-tauri 文件夹中运行以下命令,把插件加入 Cargo.toml 里的项目依赖:

    1
    
    cargo add tauri-plugin-http
    
  2. 修改 lib.rs 初始化插件:

    1
    2
    3
    4
    5
    6
    7
    
    #[cfg_attr(mobile, tauri::mobile_entry_point)]
    pub fn run() {
        tauri::Builder::default()
            .plugin(tauri_plugin_http::init())
            .run(tauri::generate_context!())
            .expect("error while running tauri application");
    }
    
  3. 用你偏好的 JavaScript 包管理器安装 JavaScript 端绑定:

1
npm install @tauri-apps/plugin-http
1
yarn add @tauri-apps/plugin-http
1
pnpm add @tauri-apps/plugin-http
1
deno add npm:@tauri-apps/plugin-http
1
bun add @tauri-apps/plugin-http

用法

HTTP 插件在 Rust 中作为 reqwest 的重新导出可用,在 JavaScript 中也可用。

JavaScript

  1. 配置允许的 URL

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    //src-tauri/capabilities/default.json
    {
      "permissions": [
        {
          "identifier": "http:default",
          "allow": [{ "url": "https://*.tauri.app" }],
          "deny": [{ "url": "https://private.tauri.app" }]
        }
      ]
    }
    

    更多信息请参阅权限概述文档。

  2. 发送请求

    fetch 方法尽可能贴近并符合 fetch Web API。

    1
    2
    3
    4
    5
    6
    7
    8
    
    import { fetch } from '@tauri-apps/plugin-http';
    
    // 发送 GET 请求
    const response = await fetch('http://test.tauri.app/data.json', {
      method: 'GET',
    });
    console.log(response.status); // 例如 200
    console.log(response.statusText); // 例如 "OK"
    

Rust

在 Rust 中你可以使用该插件重新导出的 reqwest crate。更多细节请参阅 reqwest 文档。

1
2
3
4

let res = reqwest::get("http://my.api.host/data.json").await;
println!("{:?}", res.status()); // 例如 200
println!("{:?}", res.text().await); // 例如 Ok("{ Content }")

权限

默认情况下,所有有潜在危险的插件命令和作用域都被阻止,无法访问。你必须在 capabilities 配置中修改权限才能启用它们。

更多信息请参阅能力概述,以及使用插件权限的分步指南。

1
2
3
4
5
6
{
  "permissions": [
    ...,
    "http:default"
  ]
}
最后修改 September 26, 2026: 更新 (630b11f59)