请求的时候会有各种各样的报错,比如下面等等,主要是 "errMsg":"request:fail abort statusCode:-1 看这个报错
16:11:19.304 [Vue warn]: Error in onLoad hook (Promise/async): "[object Object]"
16:11:19.342 (found at pages/index/index.vue:1)
16:11:19.363 {"errMsg":"request:fail abort statusCode:-1"}
{"errMsg":"request:fail abort statusCode:-1 不支持的URL(-1002)"} __ERROR
{"errMsg":"request:fail abort statusCode:-1 Failed to connet to localhost/127.0.0.1:8080
H5没问题的原因是用了代理,配置了跨域,所以没问题
proxy: {
'/api': {
target: 'http://101.xx.xx.xx:8090/',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
但是我们并没有配置app的跨域问题,所以请求的时候把地址写全了,app端不要这个proxy就行了,下面针对h5和app做个兼容
1. 代理的地方,只配置h5的,h5走这个代理
// #ifdef H5
server: {
proxy: {
'/api': {
target: 'http://101.xx.xx.xx:8090/',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
// #endif
2. 请求封装的地方, h5及其他baseURL是接口前缀,如果是app,把baseURL配置成接口全地址就行
let baseURL = '/api';
// #ifdef APP-PLUS
baseURL = "http://101.xx.xx.xx:8090"
// #endif
3. 然后在请求的地方做个区分就好了
uni.request({
...options,
// #ifdef APP-PLUS
url: baseURL + options.url,
// #endif
// 成功
success(res) {
},
// 失败
fail(err) {
},
})
4. 接口定义的地方还是正常用请求地址就行,比如api/user/info, 到3的app的请求url就是
http://101.xx.xx.xx:8090/api/user/info
OK了,打包出的app也能请求接口了