// 云应用ID 不同商家可能有不同的店铺。店铺的云应用iD不同
const APPS = {
default: '123456' // 默认云应用ID 123456为示例,非真实
};
/****
* 如果是模板小程序需要拿到模板id和卖家openID
*/
// let extJson = my.getExtConfigSync();
// const { templateId, sellerOpenId } = extJson;
/**
* ajax请求数据
* 1.云应用不需要完整域名,只需要接口访问路径即可。
* 2.app:调用的云应用类型,为APPS内key值。
* 3.method:云应用仅支持 GET,POST。
* 4.POST 请求仅支持 application/json json数据格式传输。
*/
export default async function ajax({
url, app = 'default', method = 'GET',
data = {},
headers = {},
params = {},
}) {
try {
const { cloud } = getApp(); // getApp获取整个应用的实例
const appId = APPS[app] || APPS.default; // 关联的云应用ID
const paramsStr = Object.keys(params).map(key => `${key}=${params[key]}`).join('&');
url = `/${url}${paramsStr ? `?${paramsStr}` : ''}`;
/**
* 如果是模板小程序
* */
// url = `/${url}?templateId=${templateId}&sellerOpenId=${sellerOpenId}${paramsStr ? `&${paramsStr}` : ''}`;
let options = {
path: url, method, headers,
exts: {
cloudAppId: appId, // 云应用iD
// timeout: 5000
},
}
options.headers = {
...options.headers,
'Content-Type': options.method === 'POST'
? 'application/json'
: 'application/x-www-form-urlencoded',
};
if (options.method === 'POST') {
options.body = data;
} else {
options.method = 'GET';
// options.params = data;
const qs = Object.keys(data)
.map(key => `${key}=${data[key]}`)
.join('&');
if (qs) url = `${url}&${qs}`;
options.path = url;
}
// console.log('options ====> ', options)
const result = await cloud.application.httpRequest(options);
// console.log(result)
return result;
} catch (e) {
console.info(url + ' error!', e);
throw e;
};
}
淘宝小程序开发——请求封装
最新推荐文章于 2024-01-24 16:26:49 发布