赞
踩
总结一下 当前request 请求 传递fromData 的写法
在我们前端调用接口的使用中 我们会传递参数 大部分是json 格式的 但是有的时候 回事 formData 的格式的 那我们前端就需要修改一下 传递对应的东西
我直接上代码了那就
我说一下我使用Taro 框架中的写法 就是移动端 和小程序中的写法
- import Taro from "@tarojs/taro";
- import { useUserStore } from "../store";
- let needLoadingRequestCount = 0;
- // loading配置,请求次数统计
- function startLoading() {
- Taro.showLoading({ title: "加载中", mask: true });
- }
- function endLoading() {
- Taro.hideLoading();
- } // 声明一个对象用于存储请求个数
- function showFullScreenLoading() {
- if (needLoadingRequestCount === 0) {
- startLoading();
- }
- needLoadingRequestCount++;
- }
- function tryHideFullScreenLoading() {
- if (needLoadingRequestCount <= 0) return;
- needLoadingRequestCount--;
- if (needLoadingRequestCount === 0) {
- endLoading();
- }
- }
- //loading是做了多个请求同时发起的时候防止动画叠加
-
- export default function request(url, config: any = {}, needLoading = false) {
- const BASE_URL = "xxxx";
- //默认加载都带动画设置false不加载
- const userStore = useUserStore();
- needLoading && showFullScreenLoading();
- return new Promise((resolve, reject) => {
- Taro.request({
- url: `${BASE_URL}${url}`,
- method: config.type.toUpperCase() || "GET",
- data: config.data || {},
- timeout: 10000,
- header: {
- "Content-type": config.paramsFormdata || "application/json",
- Authorization: userStore.Token,
- ...config.header,
- },
-
- success: (result:any) => {
- const { statusCode, data } = result;
- if (statusCode === 200) {
- if (result?.token) {
- Taro.setStorageSync("TOKEN", result?.token);
- }
- resolve(data);
- } else if (statusCode === 401) {
- Taro.removeStorageSync("TOKEN");
- Taro.removeStorageSync("userInfo");
- setTimeout(() => {
- Taro.redirectTo({
- url: "/pages/login/index",
- });
- }, 500);
- }
- },
- fail: (error) => {
- Taro.showToast({
- title: "网络错误",
- icon: "error",
- });
- return error;
- },
- complete: (res) => {
- // tryHideFullScreenLoading();
- },
- });
- });
- }
我这里有一个判断 当我需要传递这个 formData 的格式的时候
- export function EmitCodeByH5(data) {
- return requestService(Api.code, {
- type: "post",
- data,
- // paramsFormdata: "application/x-www-form-urlencoded",
- });
- }
如果不传递 paramsFormdata 就默认是json 传就是formData 的格式的
我说一下在web端中的使用 我使用的是tdesign 的框架
人家封装好的request 的文件我就不写了
直接写api 的写法
- // 假设你已经有了一个 Api.page 的 URL
- const Api = {
- page: '你的URL地址',
- };
-
- // 假设 request.post 是一个支持发送 FormData 的函数
- export function page(data: any) {
- // 创建一个 FormData 实例
- const formData = new FormData();
-
- // 假设 data 是一个包含 robotId 等属性的对象
- // 遍历 data 的属性,并添加到 formData 中
- for (const key in data) {
- if (data.hasOwnProperty(key)) {
- formData.append(key, data[key]);
- }
- }
-
- // 发送请求,将 formData 作为请求体
- return request.post({
- url: Api.page,
- data: formData, // 这里传递 formData
- // 可能还需要设置 Content-Type 为 multipart/form-data,但通常库会自动处理这个
- // headers: {
- // 'Content-Type': 'multipart/form-data'
- // },
- // 注意:某些 HTTP 客户端库(如 axios)在发送 FormData 时会自动设置正确的 Content-Type
- });
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。