Tauri 应用中发送 http 请求

最近基于 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)
    })
  })
}

欢迎访问:天问博客

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值