最近基于 TauriReact 开发一个用于 http/https 接口测试的工具 Get Tools,其中使用了 tauri 提供的 fetch API,在开发调试过程中遇到了一些权限和参数问题,在此记录下来。

Tauri Http

权限配置

tauri 应用中,如果想要使用 httpfetch API 发送请求,必须配置相应的权限和 scope。 否则会出现类似这样的报错:url not allowed on the configured scope: http://xxx.com/xxx

因此,需要在 tauri.conf.json 文件中进行配置:

{ "tauri": { "allowlist": { // ... "http": { "all": true, "request": true, "scope":[ "http://**", "https://**" ] } // ... } } }

如上所示,将 httpscope 字段配置了 http://**https://** 匹配规则,就可以发送任意的 http/ https 的接口请求了,并且不存在跨域问题。

http 请求封装

平常习惯了使用 ajaxaxios 的请求方法,所以这里对 tauri 提供的 fetch API 进行基础封装,统一 GETPOST 的请求形式和参数配置,让使用更丝滑。

// http.js import { fetch, ResponseType, Body } from '@tauri-apps/api/http' // https://tauri.app/zh-cn/v1/api/js/http#fetch export const http = (opts = {}) => { return new Promise((resolve, reject) => { const { url, method, query, data, headers, callback } = opts fetch(url, { method: method || 'GET', headers: { 'content-type': 'application/json', ...headers, }, responseType: ResponseType.JSON, timeout: 60000, query: query, body: Body.json({ ...data, }), }) .then((res) => { callback && callback(res) resolve(res) }) .catch((e) => { reject(e) }) }) }

欢迎访问:天问博客