uniapp使用原生请求访问本地服务器 |
您所在的位置:网站首页 › uniapp发送formdata › uniapp使用原生请求访问本地服务器 |
uniapp使用原生请求访问使用express框架搭建的本地服务器
简易版
async test(){
uni.request({method: "get",url: 'http://127.0.0.1:8088/recommendlist'}).then(err=>{
if(err[0]){//then是promise对象上的特有函数,第一个是成功回调,第二个失败回调
console.log("接口请求失败")
//我们也可通过成功回调返回的数组,判断是否成功,数组0位为0数据接收成功,为1接收失败
}else{
console.log("请求成功")
console.log(err[1].data)
}
})
}
该函数是我的请求函数,没有经过封装,在created()中调用的。需要注意的是async是不能直接在生命周期中使用,通过写成函数在里面调用即可。 通过async调用的函数返回的会使一个promise对象, uni.request(object)是uni的原生请求方式,配置好后用.then获取数据。第一个是成功回调函数,默认有一个参数,可根据参数判断成功与否,并获取数据。 // 利用express框架搭建一个服务器 const express =require("express"); const app =express();//创建对象 app.get('/recommendlist',(request,response)=>{ response.setHeader('Access-Control-Allow-Origin','*') //解决跨域问题 let str = JSON.stringify(recommendlist); // response.send("我看到你了哦") response.send(str) }) app.listen(8088,()=>{ console.log("服务器已经启动") })一个Promise对象如何前面加上await返回的就直接是结果,.then函数中第一个成功回调函数的参数。如果不加直接返回promise对象。 封装版本新建一个js文件 const request = (config) => { let promise = new Promise(function(resolve, reject) { uni.request(config).then(responses => { if (responses[0]) { reject({message : "网络超时"}); } else { resolve(responses[1].data); } }).catch(error => { reject(error); }) }) return promise; }; export function getTypeList () { return request({ method: "get", url: 'http://test.fugouyun.com/api/v2/temp/fruitVeg/getParamsList', }) }在主页面写如下函数,在生命周期中调用给即可(注意上面的Js文件需引入) import {getRecommendlist} from "@/utils/food" async loadData(){ console.log("我竟来啦") const data =await getRecommendlist(); console.log(data) }, |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |