一、前言:为什么小程序网络请求"不简单"?
很多开发者第一次写小程序时,会遇到这样的问题:
javascript
wx.request({
url: 'http://localhost:3000/api/user',
success(res) { console.log(res) }
})
结果控制台报错:
"request:fail url not in domain list"
这是因为微信小程序对网络请求有严格的安全限制:
- ✅ 只支持 HTTPS
- ✅ 域名必须提前在后台配置
- ❌ 不支持 IP 地址或
localhost - ❌ 不支持 HTTP(除非本地调试)
本文将手把手教你:
✅ 正确配置合法域名
✅ 使用 wx.request 发起请求
✅ 封装通用请求工具函数
✅ 处理常见错误与调试技巧
二、第一步:配置服务器域名(上线必备!)
1. 登录微信公众平台
- 访问 https://mp.weixin.qq.com
- 进入 开发管理 > 开发设置 > 服务器域名
2. 配置 request 合法域名
-
在 request 合法域名 中添加你的 API 域名,例如:
https://api.yourdomain.com -
⚠️ 注意:
- 必须是 HTTPS
- 不能带路径(只填域名)
- 不能使用 IP 或
127.0.0.1 - 域名需有有效 SSL 证书(免费可用 Let's Encrypt)
📌 开发阶段可临时绕过 :在开发者工具中勾选 "不校验合法域名"(仅限真机预览前调试)。
三、核心 API:wx.request() 详解
基础用法
javascript
wx.request({
url: 'https://api.example.com/user/profile',
method: 'GET',
header: {
'Authorization': 'Bearer xxx',
'content-type': 'application/json'
},
success(res) {
console.log('请求成功', res.data);
},
fail(err) {
console.error('请求失败', err);
}
});
常用参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
url |
string | 必须 HTTPS,且在合法域名列表中 |
method |
string | GET / POST / PUT / DELETE 等 |
data |
Object/String | 请求参数(POST 自动序列化) |
header |
Object | 请求头(注意 content-type 默认是 application/json) |
timeout |
number | 超时时间(毫秒,默认 60s) |
success/fail/complete |
Function | 回调函数 |
四、实战:封装通用请求工具(推荐!)
直接使用 wx.request 会导致代码重复。建议封装成工具函数。
1. 创建 utils/request.js
javascript
// utils/request.js
const BASE_URL = 'https://api.yourdomain.com';
function request(options) {
return new Promise((resolve, reject) => {
wx.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Authorization': wx.getStorageSync('token') || '',
'content-type': options.contentType || 'application/json'
},
timeout: 10000,
success: (res) => {
const { statusCode, data } = res;
if (statusCode === 200) {
resolve(data);
} else {
wx.showToast({ title: '服务异常', icon: 'none' });
reject(res);
}
},
fail: (err) => {
wx.showToast({ title: '网络错误', icon: 'none' });
reject(err);
}
});
});
}
// 导出常用方法
export const get = (url, data) => request({ url, data, method: 'GET' });
export const post = (url, data) => request({ url, data, method: 'POST' });
2. 在页面中使用
javascript
// pages/index/index.js
import { get, post } from '../../utils/request';
Page({
onLoad() {
this.fetchUserInfo();
},
async fetchUserInfo() {
try {
const user = await get('/user/profile');
console.log('用户信息:', user);
this.setData({ userInfo: user });
} catch (err) {
console.error('获取失败', err);
}
}
});
✅ 优势:统一处理 token、错误提示、base URL,代码更简洁!
五、常见问题与解决方案
❓ Q1:本地开发如何调用后端接口?
- 方案 A(推荐) :用内网穿透工具(如 ngrok、localtunnel)将本地服务暴露为 HTTPS 公网地址。
- 方案 B :在开发者工具中勾选 "不校验合法域名、web-view 域名、TLS 版本"(仅限开发阶段!)
⚠️ 真机预览或上线前,必须配置合法 HTTPS 域名!
❓ Q2:POST 请求参数没传过去?
-
检查
content-type:application/json→ 后端需解析 JSON bodyapplication/x-www-form-urlencoded→ 参数需encodeURIComponent
-
示例:
javascript// JSON 格式(默认) post('/login', { username: 'a', password: '123' }); // 表单格式 post('/login', 'username=a&password=123', 'application/x-www-form-urlencoded');
❓ Q3:如何携带 Token?
-
登录后将 token 存入 Storage:
javascriptwx.setStorageSync('token', res.data.token); -
在封装的 request 中自动读取并加入 Header(见上文封装示例)
❓ Q4:请求超时怎么办?
-
设置
timeout参数(单位:毫秒):javascriptwx.request({ url, timeout: 5000 }); -
用户体验:超时后提示"网络慢,请重试"
六、安全与性能最佳实践
✅ 安全建议
- 所有接口必须走 HTTPS
- 敏感操作(如支付)需二次验证
- Token 设置过期时间,避免长期有效
✅ 性能优化
- 合并请求:避免频繁小请求
- 缓存数据:用
Storage缓存不变数据(如城市列表) - 错误重试:网络失败时自动重试 1~2 次
七、结语
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!