UniApp 接口调用代码示例 - 使用 uniRequest 方法
以下是一个简单的 Uniapp 调用接口的代码示例:
// 在页面中引入uni.request方法
import uniRequest from '@/common/request.js'
// 在方法中使用uni.request调用接口
export default {
methods: {
async fetchData () {
try {
const response = await uniRequest({
url: 'https://api.example.com/data',
method: 'GET',
data: {
limit: 10,
page: 1
}
})
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
}
在上面的代码中,我们首先在页面中引入了一个 uniRequest 方法,这个方法是我们自己封装的一个 UniApp 请求方法,它会返回一个 Promise 对象。
在 fetchData 方法中,我们使用 uniRequest 方法调用了一个接口,传入了接口的地址、请求方法和请求参数。如果请求成功,我们就可以在控制台中打印出返回的数据。如果请求失败,我们就把错误信息打印出来。
需要注意的是,由于 UniApp 平台的限制,我们无法直接在页面中使用 XMLHttpRequest 或 fetch 方法来发起请求。因此,我们需要自己封装一个请求方法来处理接口调用。
原文地址: https://www.cveoy.top/t/topic/lU2q 著作权归作者所有。请勿转载和采集!