Tauri发送网络请求系列,接口请求封装并遇到的问题解决办法

文章介绍了在Tauri项目中如何配置安全域名以避免跨域问题,并展示了如何对内置的fetch方法进行二次封装,添加请求和响应处理功能,包括设置超时、构建URL、处理请求与响应数据类型等。此外,文中还给出了GET、POST及上传文件的示例代码。
摘要由CSDN通过智能技术生成

接口请求处理
项目中没有使用 axios 等前端 HTTP 请求库,使用的是 Tauri 内置的 fetch 方法,但该方法使用比较简单,没有请求拦截器或响应拦截器相关配置,所以我们有必要在此基础上做下二次封装。

1. 配置安全域名
在 tauri.conf.json 里添加配置

        "allowlist": {
            "all": true,
            "http": {
                "scope": ["http://**", "https://**"]
            },
            "shell": {
                "all": false,
                "open": true
            }
        },

 红框选中的内容是必须改的,不然会发生跨域:

2. 封装 http 请求

新建 utils/http.ts 文件

import { fetch } from '@tauri-apps/api/http'

const baseURL = `你的服务器地址`

const BODY_TYPE = {
    Form: 'Form',
    Json: 'Json',
    Text: 'Text',
    Bytes: 'Bytes',
}

const commonOptions = {
    timeout: 60,
}

const isAbsoluteURL = (url: string): boolean => {
    return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

const combineURLs = (baseURL: string, relativeURL: string): string => {
    return relativeURL
        ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
        : baseURL
}

const buildFullPath = (baseURL: string, requestedURL: string) => {
    if (baseURL && !isAbsoluteURL(requestedURL)) {
        return combineURLs(baseURL, requestedURL)
    }
    return requestedURL
}

const http = (url: string, options: any = {}) => {
    if (!options.headers) options.headers = {}
    if (options?.body) {
        if (options.body.type === BODY_TYPE.Form) {
            options.headers['Content-Type'] = 'multipart/form-data'
        }
    }

    options = { ...commonOptions, ...options }
    return fetch(buildFullPath(baseURL, url), options)
        .then(({ status, data }) => {
            if (status >= 200 && status < 400) {
                return { data }
            }
            return Promise.reject({ status, data })
        })
        .catch((err) => {
            console.error(err)
            return Promise.reject(err)
        })
}

export default http

3.简单实用

这里要注意,发送请求前,就要知道返回的数据类型:下面三种

不然会发生错误。

as JSON: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON;
              try setting the `responseType` option to `ResponseType.Text` or `ResponseType.Binary` if the API does not return a JSON response.
    at chunk-YIDC66OP.js:1:1532

 这是因为没有指定响应的数据类型,需要添加一下: responseType: http.ResponseType.Text

GET:

import http from '@/utils/http';

const params = {};

http('https://www.baidu.com/get', {
  method: 'get',
  params,
});

 POST:

import { Body } from '@tauri-apps/api/http';
import http from '@/utils/http';

const body = Body.json({
  test: '1',
});

http('https://www.baidu.com/post', {
  method: 'post',
  body,
});

POST 上传文件

import { Body } from '@tauri-apps/api/http';
import http from '@/utils/http';

const generateFileInfo = (
  arrayBuffer: any,
  mime: string,
  fileName: string,
) => {
  return {
    file: new Uint8Array(arrayBuffer),
    mime,
    fileName,
  };
};

const arrayBuffer = await file.arrayBuffer();
const body = Body.form({
  file: generateFileInfo(arrayBuffer, file.type, file.name),
  // todo 其他参数
});

http('https://www.baidu.com/upload', {
  method: 'post',
  body,
});

带数据类型的请求:

async function getData() {
    const params = {}
    const res = await http('https://www.baidu.com', {
        method: 'get',
        params,
        responseType: ResponseType.Text,
    })
    console.log('返回的数据是:', res)
}

请求到的数据:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1024小神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值