Skip to content

发送请求

网络请求

在 uni 中可以调用 uni.request 方法进行请求网络请求

需要注意的是:在小程序中网络相关的 API 在使用前需要配置域名白名单。

发送 get 请求 发送 post 请求

示例

html
<template>
  <view>
    <button @click="sendGet">发送请求</button>
  </view>
</template>
<script>
  export default {
      methods: {
          sendGet () {
              uni.request({
                  url: 'http://localhost:8082/api/getlunbo',
          data: 请求的参数,
          header:设置请求的头部,header中不能设置Referer
          method:'GET', //GET捉着POST
          dataType:'json' //如果设置为json,会尝试对返回的数据做一次JSON.parse
                  success(res) {
                      console.log(res)
                  },
          fail(res){
            console.log(res)
          }
              })
          }
      }
  }
</script>

封装 request.js

js
import constants from "./constants";
import { md5 } from "js-md5";
const request_url = "这里填写后台接口域名";
const BAER_URL = request_url;
class Request {
  constructor() {}
  request(method, api, formData, showLoading) {
    showLoading && uni.showLoading({ title: "加载中..." });
    return new Promise((resolve, reject) => {
      let randomstr = this.getrndomstr(16);
      let timestamp = this.gettimestamp();
      let sign = md5(randomstr + "请填写加密字符串" + timestamp);
      uni.request({
        url: BAER_URL + api,
        method,
        data: formData,
        header: {
          "content-type": "application/json", // 默认值
          token: uni.getStorageSync(constants.TOKEN) || "",
          randomStr: randomstr,
          timesTamp: timestamp,
          sign: sign,
        },
        success: (res) => {
          // 成功
          if (res.data.code === 200) {
            showLoading && uni.hideLoading();
            resolve(res.data.data);
            //  [401, 502].includes(Number.parseInt(res.data.code))
          } else if (res.data.code === 1001) {
            // 登录过期
            uni.clearStorageSync();
            uni.$tools.showToastCall(
              {
                title: res.data.message,
                icon: "none",
              },
              () => {
                uni.$tools.toLogin();
              }
            );
          } else {
            // 其他状态码
            uni.showToast({
              title: res.data.message || "服务器开小差",
              icon: "none",
            });
            reject(res);
          }
        },
        fail: (err) => {
          // 失败
          console.log(err);
          reject(err);
          uni.showToast({
            title: err.errMsg,
            icon: "none",
          });
        },
      });
    });
  }
  get(api, formData) {
    return this.request("GET", api, formData);
  }
  post(api, formData, showLoading = true) {
    return this.request("POST", api, formData, showLoading);
  }
  upload(api, filePath) {
    // 文件上传
    uni.showLoading({ title: "上传中..." });
    let uploads = [];
    let filePaths;
    typeof filePath === "string"
      ? (filePaths = [filePath])
      : (filePaths = filePath); // 全转数组 遍历
    for (let i = 0; i < filePaths.length; i++) {
      uploads[i] = new Promise((resolve, reject) => {
        uni.uploadFile({
          url: BAER_URL + api,
          filePath: filePaths[i],
          header: {
            token: uni.getStorageSync(constants.TOKEN) || "",
          },
          name: "file", // 字段名
          success: (res) => {
            const data = JSON.parse(res.data);
            if (res.statusCode === 200 && data.code === 1) {
              resolve(data.data);
            } else {
              // 其他状态码
              reject(data);
            }
          },
          error: (e) => {
            reject(e);
          },
        });
      });
    }
    return new Promise((resolve, reject) => {
      Promise.all(uploads)
        .then((res) => {
          // console.log('all upload done', res)
          uni.hideLoading();
          resolve(res); // 所有文件上传成功回调
        })
        .catch((e) => {
          uni.showToast({
            title: e.msg || "图片上传失败",
            icon: "error",
          });
          reject(e);
        });
    });
  }

  /**
   * 随机字符串
   * @param length
   * @returns {string}
   */
  getrndomstr(length) {
    let characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let randomString = "";
    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      randomString += characters.charAt(randomIndex);
    }
    return randomString;
  }

  /**
   * 秒级时间戳
   * @returns {number}
   */
  gettimestamp() {
    let timestamp = Math.floor(Date.now() / 1000);
    return timestamp;
  }
}

const request = new Request();

export default request;

调用

  • js 调用接口
js
import request from "@/lib/request";

/**
 * 接口示例
 * @param {*} params
 */
export const testapi = (params) => {
  return request.post("api/testapi/testapi");
};
  • page 下面调用
js
onLoad() {
  testapi({
    name: "test",
  })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
}