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)
}

请求到的数据:

相关推荐
天天扭码6 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子6 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing7 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼7 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长8 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs8 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队9 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_471199639 小时前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript
Curvatureflight9 小时前
前端性能优化实战:从3秒到300ms的加载速度提升
前端·人工智能·性能优化