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

请求到的数据:

相关推荐
辻戋1 小时前
从零实现React Scheduler调度器
前端·react.js·前端框架
徐同保1 小时前
使用yarn@4.6.0装包,项目是react+vite搭建的,项目无法启动,报错:
前端·react.js·前端框架
Qrun2 小时前
Windows11安装nvm管理node多版本
前端·vscode·react.js·ajax·npm·html5
中国lanwp2 小时前
全局 npm config 与多环境配置
前端·npm·node.js
JELEE.3 小时前
Django登录注册完整代码(图片、邮箱验证、加密)
前端·javascript·后端·python·django·bootstrap·jquery
TeleostNaCl5 小时前
解决 Chrome 无法访问网页但无痕模式下可以访问该网页 的问题
前端·网络·chrome·windows·经验分享
前端大卫7 小时前
为什么 React 中的 key 不能用索引?
前端
你的人类朋友7 小时前
【Node】手动归还主线程控制权:解决 Node.js 阻塞的一个思路
前端·后端·node.js
小李小李不讲道理9 小时前
「Ant Design 组件库探索」五:Tabs组件
前端·react.js·ant design
毕设十刻9 小时前
基于Vue的学分预警系统98k51(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js