跳转到内容
Tauri

HTTP 客户端

使用 HTTP 插件发起 HTTP 请求。

设置

请安装 http 插件。

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

npm run tauri add http

用法

http 插件既有 JavaScript API 版本,也有 Rust reqwest 重新导出的版本。

JavaScript

  1. 配置允许访问的 URL

    src-tauri/capabilities/base.json
    {
    "permissions": [
    {
    "identifier": "http:default",
    "allow": [{ "url": "https://*.tauri.app" }],
    "deny": [{ "url": "https://private.tauri.app" }]
    }
    ]
    }

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

  2. 发送请求

    import { fetch } from '@tauri-apps/plugin-http';
    // Send a GET request
    const response = await fetch('http://my.api.host/data.json', {
    method: 'GET',
    });
    console.log(response.status); // e.g. 200
    console.log(response.statusText); // e.g. "OK"

Rust

在 Rust 中,你可以利用插件重新导出的 reqwest 包。更多细节请参考 reqwest 文档

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

© 2024 Tauri Contributors. CC-BY / MIT