uniapp开发H5和APP封装接口请求?
用uniapp 写APP、怎么接口请求错误了,在H5上面是能请求成功的
const pre = "Bearer ";
const request = (options = {}) => {
let token = uni.getStorageSync("token");
options.header["Accept"] = "application/json, text/plain, */*";
options.header["Authori-zation"] = pre + uni.getStorageSync("token");
return new Promise((resolve, reject) => {
//获取接口的全连接
uni.request({
url: options.url, //仅为示例,并非真实接口地址。
method: options.type || "GET",
data: options.data || {},
header: options.header || {},
success: (res) => {
const { code, result, other, msg, status } = res.data;
if (status == 410000 || status == 410001 || status == 410002) {
uni.clearStorage();
resolve({ msg, status, result });
return
}
if (status !== 200 && options.loading) {
uni.showToast({
title: msg,
icon: "error",
});
resolve({ msg, status, result });
} else {
resolve({ result, other, msg, status });
}
},
complete: (e) => {
if (options.loading) {
uni.hideLoading();
}
},
});
});
};
const post = (
url,
data,
loading = true,
options = {
header: {},
}
) => {
options.type = "POST";
options.data = data;
options.url = url;
options["loading"] = loading;
options.header["content-type"] = "application/json";
return request(options);
};
export { post };
在手机模拟器上面报错的信息是:
{"errMsg":"request:fail abort statusCode:-1 Expected URL scheme 'http' or 'https' but was 'file'"}
回复
1个回答
test
2024-06-21
请求的URL是什么呢?看报错信息是发起的是 file
协议?
还是说你请求的地址没有拼写完全?把你的 baseUrl
设置为完整的地址呢?比如说 https://xxx.xxx.xxx.xx/api
这样。可能你H5可以是你本地有启动HTTP服务,所以你省略了请求地址前的域名信息?浏览器是会按照当前的域名自动拼接的,APP应该不会拼接。
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容