Skip to content

网络请求

小程序没有 fetch,网络能力统一走 wx.request(及 request 的变体)。封装一个好用的请求层是所有项目的第一课。这篇从 API 到工程封装完整讲。

一、wx.request 基础

js
wx.request({
  url: 'https://api.example.com/v1/products',
  data: { page: 1, size: 20 },
  header: { 'content-type': 'application/json', 'Authorization': 'Bearer ' + token },
  method: 'GET',
  timeout: 60000,
  dataType: 'json',
  responseType: 'text',
  enableHttp2: false,
  success(res) {
    // res.statusCode / res.data / res.header
  },
  fail(err) {
    // 网络错误、超时、域名不合法
  },
  complete() {}
});

要点:

  • 只支持 HTTPS(http 会在开发工具报错,真机直接失败)
  • 域名必须在 mp 后台配置白名单(request 合法域名),一个月内可修改 50 次,规划好测试/生产域名
  • timeout 默认 60s,最大 300s;调试接口超时优先查后端而不是调大它
  • header 里的 Referer 由微信固定注入(https://servicewechat.com/{appid}/{version}/page-frame.html),后端做防盗链/统计可能依赖它
  • 开发期勾选"不校验合法域名"可在工具里联调本地服务,上线前务必关掉

二、封装一个请求层

裸用 wx.request 会有四个重复问题:token 注入、统一错误处理、业务码分发、loading 管理。封装:

js
// utils/request.js
const BASE_URL = 'https://api.example.com';

function request(options) {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token');
    wx.request({
      url: BASE_URL + options.url,
      data: options.data || {},
      method: options.method || 'GET',
      header: {
        'content-type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
        ...(options.header || {})
      },
      timeout: options.timeout || 15000,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          const body = res.data;
          if (body && typeof body.code !== 'undefined' && body.code !== 0) {
            // 业务错误:统一处理,再决定 reject 还是 resolve
            handleBizError(body, reject);
            return;
          }
          resolve(body.data !== undefined ? body.data : body);
        } else if (res.statusCode === 401) {
          handleUnauthorized();
          reject({ type: 'auth', statusCode: 401 });
        } else {
          reject({ type: 'http', statusCode: res.statusCode });
        }
      },
      fail(err) {
        reject({ type: 'network', err });
      }
    });
  });
}

function handleBizError(body, reject) {
  if (body.code === 40101) {
    handleUnauthorized();
  } else {
    wx.showToast({ title: body.message || '请求失败', icon: 'none' });
  }
  reject({ type: 'biz', code: body.code, message: body.message });
}

function handleUnauthorized() {
  // 清理登录态,跳登录页(注意避免重复跳转)
  wx.removeStorageSync('token');
  const pages = getCurrentPages();
  const cur = pages[pages.length - 1];
  if (cur && cur.route !== 'pages/login/index') {
    wx.reLaunch({ url: '/pages/login/index' });
  }
}

module.exports = {
  get: (url, data) => request({ url, data, method: 'GET' }),
  post: (url, data) => request({ url, data, method: 'POST' }),
  put: (url, data) => request({ url, data, method: 'PUT' }),
  delete: (url, data) => request({ url, data, method: 'DELETE' }),
  request
};

使用:

js
const { get } = require('../../utils/request');

Page({
  async onLoad() {
    try {
      const list = await get('/products', { page: 1 });
      this.setData({ list });
    } catch (e) {
      // 网络/业务错误已在封装层提示,这里做页面级兜底
      this.setData({ error: true });
    }
  }
});

2.1 拦截器模式

复杂项目(多环境 baseURL、灰度 header、traceId)可以升级成实例化拦截器:

js
function createHttp(defaults) {
  const interceptors = { request: [], response: [] };

  function applyInterceptors(chain, config) {
    return chain.reduce((cfg, fn) => fn(cfg) || cfg, config);
  }

  function core(options) {
    const config = applyInterceptors(interceptors.request, { ...defaults, ...options });
    return new Promise((resolve, reject) => {
      wx.request({
        ...config,
        success: (res) => {
          const cfg2 = applyInterceptors(interceptors.response, { res, config });
          cfg2.error ? reject(cfg2.error) : resolve(cfg2.data);
        },
        fail: (err) => reject(err)
      });
    });
  }

  core.use = (type, fn) => interceptors[type].push(fn);
  return core;
}

const http = createHttp({ baseURL: 'https://api.example.com' });

// 注入 traceId
http.use('request', (config) => {
  config.header = { ...config.header, 'X-Trace-Id': genTraceId() };
  return config;
});

三、登录态与 token 刷新

小程序的登录链路:wx.login 拿 code → 服务端用 code 换 openid/session_key → 服务端签发自有 token → 前端存储使用。session_key 由服务端保管,前端永远不接触。

token 过期要做无感刷新,标准模式是请求队列 + 单飞刷新:

js
let refreshing = false;
let waitQueue = [];

function requestWithAuth(options) {
  const token = wx.getStorageSync('token');
  if (token) return request(options);

  if (refreshing) {
    return new Promise((resolve, reject) => {
      waitQueue.push({ resolve, reject, options });
    });
  }

  refreshing = true;
  return doLogin().then((newToken) => {
    wx.setStorageSync('token', newToken);
    return request(options);
  }).finally(() => {
    refreshing = false;
    const queue = waitQueue;
    waitQueue = [];
    queue.forEach(({ resolve, reject, options }) => {
      request(options).then(resolve, reject);
    });
  });
}

function doLogin() {
  return new Promise((resolve) => {
    wx.login({
      success: (res) => {
        // res.code 传给服务端
        request({ url: '/auth/login', method: 'POST', data: { code: res.code } })
          .then((data) => resolve(data.token));
      }
    });
  });
}

关键点:刷新期间并发的请求排队等待而不是各刷各的;刷新完成后统一重放。

四、并发控制

小程序 wx.request 有并发上限(同域名约 10 个,超过会排队或失败,版本间行为有差异)。批量请求要自己限流:

js
// 简易并发池:最多 3 个同时进行
function createPool(limit = 3) {
  let running = 0;
  const queue = [];

  function next() {
    if (running >= limit || !queue.length) return;
    running++;
    const { task, resolve, reject } = queue.shift();
    task().then(resolve, reject).finally(() => {
      running--;
      next();
    });
  }

  return (task) => new Promise((resolve, reject) => {
    queue.push({ task, resolve, reject });
    next();
  });
}

const pool = createPool(3);
const results = await Promise.all(ids.map(id => pool(() => get(`/detail/${id}`))));

五、超时、重试与弱网

移动网络下超时和失败是常态。分级策略:

场景策略
读接口(GET)超时 10–15s,失败静默重试 1 次(指数退避 1s、3s)
写接口(POST)默认不自动重试(幂等性问题),由用户手动重试
支付/下单不重试 + 明确结果页,防止重复下单
弱网提示wx.onNetworkStatusChange 监听,切弱网时降级图片质量、暂停预加载
js
function withRetry(task, times = 1, delay = 1000) {
  return task().catch((err) => {
    if (times <= 0) throw err;
    return new Promise((r) => setTimeout(r, delay))
      .then(() => withRetry(task, times - 1, delay * 2));
  });
}

幂等设计:写操作让服务端支持幂等键(客户端生成 uuid 放 header),重试才不会重复扣款/重复创建。

六、上传与下载

js
// 上传:进度回调 + 服务端返回 fileId
wx.uploadFile({
  url: 'https://api.example.com/upload',
  filePath: tempFilePath,
  name: 'file',
  formData: { type: 'avatar' },
  success: (res) => { /* res.data 是字符串,要 JSON.parse */ },
  fail: () => {}
});

// 下载:大文件用 downloadTask 监听进度
const task = wx.downloadFile({
  url: fileUrl,
  success: (res) => {
    if (res.statusCode === 200) {
      wx.saveFileToDisk ? wx.saveFileToDisk({ filePath: res.tempFilePath }) : null;
    }
  }
});
task.onProgressUpdate(({ progress, totalBytesWritten, totalBytesExpectedToSend }) => {
  this.setData({ uploadPercent: progress });
});

坑点:uploadFile 的 success.data 是字符串(不是对象),记得 parse;下载的临时文件有有效期,要及时 saveFile 转持久化;超过 10MB 的文件用分片上传,服务端合并。

七、请求取消

页面销毁时取消未完成的请求,避免回调操作已销毁页面:

js
Page({
  data: {},
  onLoad() {
    this.tasks = [];
    const t = wx.request({ /* ... */ });
    this.tasks.push(t);
  },
  onUnload() {
    this.tasks.forEach(t => t.abort && t.abort());
    this.tasks = [];
  }
});

封装层更优的做法:给每个请求分配 requestId,页面 onHide/onUnload 时批量 abort。

八、常见问题

Q:报 "不在以下 request 合法域名列表中"? mp 后台 → 开发管理 → 服务器域名 → request 合法域名,只支持 https,域名不带路径。开发工具里可临时勾选不校验。

Q:真机和工具结果不一样? 工具不严格校验证书链和 TLS 版本;真机要求合法 CA 证书 + TLS 1.2。自签名证书真机必挂。

Q:response 返回乱码?dataType 设 json 时服务端必须返回 content-type: application/json;中文乱码检查服务端 charset。

相关阅读

CTO Plus技术栈 Version 1.0.20261024-12