网络请求
原创2026/3/5大约 2 分钟

发起 HTTPS 网络请求,从后端获取数据,显示在页面之上
基本使用
通过wx.request请求数据
Page({
onLoad(options) {
wx.request({
url: 'https://iwenwiki.com/api/blueberrypai/getChengpinDetails.php',
success(res) {
console.log(res.data)
},
})
},
})注意
在小程序中使用网络相关的 API 时,需要注意下列问题,请开发者提前了解
每个微信小程序需要事先设置通讯域名,小程序只可以跟指定的域名进行网络通信(生产环境)
通过开发者工具配置:“不效验合法域名” (开发环境)
常用参数
我们了解了基本的网络请求之后,在考虑在网络请求中的属性如何使用。例如:如何传递参数?
| 属性 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| url | string | 是 | 开发者服务器接口地址 | |
| data | string/object/ArrayBuffer | 否 | 请求的参数 | |
| header | Object | 否 | 设置请求的 header,header 中不能设置 Referer。 content-type 默认为 application/json | |
| timeout | number | 否 | 超时时间,单位为毫秒。默认值为 60000 | |
| method | string | GET | 否 | HTTP 请求方法 常用的方式 GET 和 POST |
| success | function | 否 | 接口调用成功的回调函数 | |
| fail | function | 否 | 接口调用失败的回调函数 | |
| complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
Page({
data: {
chengpinDetails: [],
},
onLoad() {
wx.request({
url: 'http://iwenwiki.com:3002/api/foods/list',
method: 'GET',
data: {
city: '北京',
},
header: {
'content-type': 'application/json',
},
timeout: 5000,
success(res) {
console.log(res.data)
},
fail(error) {
console.log(error)
},
complete() {
console.log('网络请求完成')
},
})
},
})封装网络请求
新建 /api/request.ts 文件
function request(url: any, method: any, data: any) {
wx.showLoading({
title: '加载中...',
mask: true,
})
const promise = new Promise((resolve, reject) => {
wx.request({
url: url,
method: method,
data: data,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
success(res) {
resolve(res)
},
fail(err) {
reject(err)
},
complete() {
wx.hideLoading()
},
})
})
return promise
}
module.exports = {
request,
}
export {}新建 /api/index.ts 文件
const { request } = require('./request')
const base = {
baseUrl: 'http://iwenwiki.com:3002',
getList: '/api/foods/list', // 获取列表接口
toLogin: '/api/user/login', // 登录接口
}
function getList(data: any) {
return request(base.baseUrl + base.getList, 'GET', data)
}
function toLogin(data: any) {
return request(base.baseUrl + base.toLogin, 'POST', data)
}
module.exports = {
getList,
toLogin,
}
export {}使用
const { getList } = require('../../api/index')
Page({
data: {
chengpinDetails: [],
},
onLoad() {
getList({ city: '北京' }).then((res: any) => {
console.log(res.data)
})
},
})至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。