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

接口请求处理

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

1. 配置安全域名

在 tauri.conf.json 里添加配置

json 复制代码
        "allowlist": {
            "all": true,
            "http": {
                "scope": ["http://**", "https://**"]
            },
            "shell": {
                "all": false,
                "open": true
            }
        },

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

2. 封装 http 请求

新建 utils/http.ts 文件

javascript 复制代码
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:

javascript 复制代码
import http from '@/utils/http';

const params = {};

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

POST:

javascript 复制代码
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 上传文件

javascript 复制代码
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,
});

带数据类型的请求:

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

请求到的数据:

相关推荐
熊的猫18 分钟前
校招生问我在vue中,什么时候该用 render 函数?
前端·javascript·vue.js
striver_#33 分钟前
京东前端社招面经
前端·面试
掘金安东尼34 分钟前
用 CSS random() 来掷骰子
前端·css·面试
前端小巷子35 分钟前
Vue 事件系统
前端·vue.js·面试
訾博ZiBo41 分钟前
VibeCoding 时代来临:如何打造让 AI 秒懂、秒改、秒验证的“AI 友好型”技术栈?
前端·后端
excel1 小时前
彻底理解缓冲区:从概念、背压到可运行的 Fetch 流式示例
前端
小蜜蜂嗡嗡3 小时前
【flutter对屏幕底部有手势区域(如:一条横杠)导致出现重叠遮挡】
前端·javascript·flutter
伍哥的传说4 小时前
Vue 3 useModel vs defineModel:选择正确的双向绑定方案
前端·javascript·vue.js·definemodel对比·usemodel教程·vue3.4新特性·vue双向绑定
胡gh9 小时前
页面卡成PPT?重排重绘惹的祸!依旧性能优化
前端·javascript·面试
言兴10 小时前
# 深度解析 ECharts:从零到一构建企业级数据可视化看板
前端·javascript·面试