前言
- 小程序只支持 https
- 需要到小程序后臺配置域名白名單
- 項目中請求了非 https 和不在域名白名單上的接口會報錯
- 開發(fā)時可以取消域名校驗(yàn),就可以請求任意接口,設(shè)置方法
小程序右上角詳情 =》本地設(shè)置 => 不校驗(yàn)合法域名...
(一) 發(fā)送請求
文檔地址 文檔首頁 => api => 網(wǎng)絡(luò) => 發(fā)起請求
// 示例
wx.request({
url: "test.php", //僅為示例弟胀,并非真實(shí)的接口地址
data: {
x: "",
y: ""
},
method: "get", // 也可以是post
header: {
"content-type": "application/json" // 默認(rèn)值
},
// 成功的回調(diào)
success(res) {
console.log(res.data);
},
// 失敗的回調(diào)
fail(error) {
console.log(error);
},
// 不管是成功還是失敗都會調(diào)用此方法
complete() {
console.log("done");
}
});
(二) 使用 promise 封裝請求
-
配置baseUrl
// config.js
let env = 'prod';
let baseUrl = "";
if (env === "dev") {
// 本地地址
baseUrl = "https://localhost:3009"
} else if (env === "prod") {
baseUrl = "https://huruqing.cn:3009"
}
// 導(dǎo)出
export { baseUrl }
2. ##### 新建/utils/reques.js 文件,內(nèi)容如下
```js
import { baseUrl } from "./config.js";
/**
* 封裝請求
* url:請求地址
* data:請求參數(shù)
* method: 請求類型
*/
const request = (url, data, method) => {
// 獲取token,登錄時存的
let token = wx.getStorageSync("token");
url = baseUrl + url;
return new Promise((resolve, reject) => {
// 請求
wx.request({
url,
method,
data,
header: {
"user-token": token
},
success: res => {
if (res.data.code == 666) {
resolve(res.data);
} else if (res.data.code == 603) {
wx.removeStorageSync("token");
wx.showModal({
title: "提示",
content: "登錄已過期,是否重新登錄",
success(res) {
if (res.confirm) {
// 跳轉(zhuǎn)到個人中心頁面
wx.switchTab({
url: "/pages/my/my"
});
} else if (res.cancel) {
console.log("用戶點(diǎn)擊取消");
}
}
});
} else {
reject(res.data.msg);
}
},
fail: err => {
reject("網(wǎng)絡(luò)異常");
}
});
});
};
const get = (url, data) => {
return request(url, data, "get");
};
const post = (url, data) => {
return request(url, data, "post");
};
export default {
get,
post
};
- 掛載到 app,在頁面中就不需要重復(fù)加載
// app.js
import request from "./utils/request.js";
App({
onLaunch: function() {
this.$get = request.get;
this.$post = request.post;
}
});
-
在頁面中使用
// my.js // 獲取app對象 const app = getApp(); Page({ onShow() { this.getData(); }, // 發(fā)送請求 getData() { let url = "xxxxx"; let data = { xxx: xxx }; app .$get(url, data) .then(res => { console.log(res); }) .catch(err => { console.log(err); }); } });