uni-app请求后端接口和请求 比眉伴天荒 2022-12-24 08:55 252阅读 0赞 # 后端接口是第三方涉及跨域问题,由于我自己没有后台服务器,无法采用cors进行设置响应头,所以采用和vue原理一样的nginx代理 # 例如要请求的地址是**http://ceshi3.dishait.cn/api/index\_category/data** 首先在配置文件 "h5": { "devServer": { "port": 8009, "disableHostCheck": true, "proxy": { "/api": { "pathRewrite":{ "^/api":"/"}, "target": "http://ceshi3.dishait.cn/api", "changeOrigin": true, "secure": false //http://ceshi3.dishait.cn/api/index_category/data } } } } 浏览器会有跨域问题,使用uniapp内置浏览器调试,注意要获取数据需要用到异步请求,返回一个promise对象 ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTUxMTIzNg_size_16_color_FFFFFF_t_70] ## 方法一,利用官网的uni.request方法 ## uni.getSystemInfo({ success:(res) =>{ res.windowHeight - uni.upx2px(80); } }) uni.request({ url: '/api/index_category/data', method: 'GET', success: res => { console.log(res); }, fail: () => { console.log('请求失败'); }, complete: () => { console.log('请求完成'); } }) ## promise请求 ## uni.request({ url: '/api/index_category/data123', method: 'GET' }).then(data=>{ let [error,result] = data // 错误 if (error) { return console.log(error.errMsg); } // 失败 if(result.statusCode !== 200){ return console.log(result.data.msg); //错误信息 } // 成功 console.log(result.data); }) ## Await 与Async ## async onLoad(){ let [error,result] = await uni.request({ url: '/api/index_category/data123', method: 'GET' }) // 错误 if (error) { return console.log(error.errMsg); } // 失败 if(result.statusCode !== 200){ return console.log(result.data.msg); //错误信息 } // 成功 console.log(result.data); } ## 封装promise,返回promise对象 ## async onload(){ return await new Promise((resolve, reject)=>{ uni.request({ url: '/api/index_category/data123', method: 'GET' }).then(data=>{ let [error,result] = data // 错误 if (error) { return console.log(error.errMsg); } // 失败 if(result.statusCode !== 200){ return console.log(result.data.msg); //错误信息 } // 成功 console.log(result.data); }) }) } [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTUxMTIzNg_size_16_color_FFFFFF_t_70]: /images/20221120/fbb55b2ed01c47ed9f72ed8a970e2a73.png
还没有评论,来说两句吧...