uni-app調取接口的3種方式以及封裝uni.request()詳解
一、uni-app中調取接口的三種方式
1、uni.request({})
uni.request({
url:'/api/getIndexCarousel.jsp',
method:'get',
success:res=>{
console.log(res.data);
this.carouselData = res.data
}
})2、uni.request({}).then()
uni.request({
url:'/api/getIndexCarousel.jsp',
method:'get',
}).then((result)=>{
let [error,res] = result;
//result將返回一個數(shù)組[error,{NativeData}]
//NativeData:調取接口后返回的原生數(shù)據(jù)
if(res.statusCode === 200){
this.carouselData = res.data
}
if(res.statusCode === 404){
console.log('請求的接口沒有找到');
}
})
3、async/await
async:用在函數(shù)定義的前面
async request(){ //函數(shù)體;}
await:用在標明了async關鍵字的函數(shù)內部,異步操作的前面。
onLoad() {
this.request();
},
methods: {
async request(){
let result = await uni.request({
url:'/api/getIndexCarousel.jsp'
})
console.log(result)
let [err,res] = result;
if(res.statusCode === 200){
this.carouselData = res.data;
}
}
}二、封裝uni.request();
1、創(chuàng)建一個對象,將該對象掛在Vue的原型下
新建@/common/request.js文件
初步寫法(僅供參考):
export default {
request(options){
uni.request({
...options,
success:res=>{
console.log(res)
}
})
},
get(url,data={},options={}){
options.url=url,
options.data=data,
options.method='get',
this.request(options)
},
post(url,data={},options={}){
options.url=url,
options.data=data,
options.method='post',
this.request(options)
}
}二次更改:
export default{
//封裝uni.request():
request(options){
return new Promise((resolve,reject)=>{
//書寫異步操作的代碼
uni.request({
...options,
success:res=>{
if(options.native){
resolve(res) //調取接口后返回的原生數(shù)據(jù)
}
if(res.statusCode === 200){
resolve(res.data) //異步操作執(zhí)行成功
}else{
console.log('請求的接口沒有找到');
reject(res) //異步操作執(zhí)行失敗
}
}
})
})
},
get(url,data={},options={}){
options.url=url;
options.data=data;
options.method='get';
return this.request(options)
},
post(url,data={},options={}){
options.url=url;
options.data=data;
options.method='post';
return this.request(options)
}
}2、進入main.js文件
import request from '@/common/request.js'; Vue.prototype.$Z = request;
例:在任意文件中書寫下列代碼可以調用。this.$Z.get();
3、在頁面中調用
//封裝uni.request():
this.$Z.get('/api/getIndexCarousel.jsp',{},{
native:false
}).then(res=>{
//異步操作成功
console.log(res)
}).catch(res=>{
//異步操作失敗
console.log(res)
}).finally(res=>{
//異步操作完成
});uniapp的網絡請求方法
uni.request({
url: 'https://www.example.com/request', //僅為示例,并非真實接口地址。
data: {
name: 'name',
age: 18
},
header: {
'custom-header': 'hello' //自定義請求頭信息
},
success: function (res) {
console.log(res.data);
}
});uniapp網絡請求的get和post
- 對于 GET 方法,會將數(shù)據(jù)轉換為 query string。例如 { name: ‘name’, age: 18 } 轉換后的結果是 name=name&age=18。
- 對于 POST 方法且 header[‘content-type’] 為 application/json 的數(shù)據(jù),會進行 JSON 序列化。
- 對于 POST 方法且 header[‘content-type’] 為 application/x-www-form-urlencoded 的數(shù)據(jù),會將數(shù)據(jù)轉換為 query string。
請求的 header 中 content-type 默認為 application/json
注意 post請求必須加header[‘content-type’]
uni-app 封裝接口request請求
我們知道一個項目中對于前期架構的搭建工作對于后期的制作有多么重要,所以不管做什么項目我們拿到需求后一定要認真的分析一下,要和產品以及后臺溝通好,其中尤為重要的一個環(huán)節(jié)莫過于封裝接口請求了。因為前期封裝好了,后面我們真的可以實現(xiàn)粘貼復制了。所以今天給大家分享一個在uni-app中如何封裝一個request請求。
第一步、根目錄下新建 config.js 文件
const config = {
base_url: '這里可以是生產環(huán)境或者測試環(huán)境'
}
export { config }這里主要配置接口的基本路徑
第二步、根目錄下新建 utils/http.js 文件
import {
config
} from '../config.js'
export const apiResquest = (prams) => { //prams 為我們需要調用的接口API的參數(shù) 下面會貼具體代碼
// 判斷請求類型
let headerData = {
'content-type': 'application/json'
}
let dataObj = null
//因為我們的GET和POST請求結構不同這里我們做處理,大家根據(jù)自己后臺接口所需結構靈活做調整吧
if (prams.method === "GET") {
headerData = {
'content-type': 'application/json',
'token': uni.getStorageSync('token')
}
} else {
dataObj = {
'data': prams.query,
'token': uni.getStorageSync('token')
}
}
return new Promise((resolve, reject) => {
let url = config.base_url + prams.url; //請求的網絡地址和局地的api地址組合
uni.showLoading({
title: '加載中',
mask: true
})
return uni.request({
url: url,
data: dataObj,
method: prams.method,
header: headerData,
success: (res) => {
uni.hideLoading()
//這里是成功的返回碼,大家根據(jù)自己的實際情況調整
if (res.data.code !== '00000') {
uni.showToast({
title: '獲取數(shù)據(jù)失敗:' + res.data.msg,
duration: 1000,
icon: "none"
})
return;
}
resolve(res.data);
console.log(res.data)
},
fail: (err) => {
reject(err);
console.log(err)
uni.hideLoading()
},
complete: () => {
console.log('請求完成')
uni.hideLoading()
}
});
})
}第三步、 創(chuàng)建model 層 根目錄下新建 models/index.js 文件
——-??注意: 這里可以根據(jù)自己的項目功能需求分解models 層——-
import { apiResquest } from '../utils/http.js'
//POST 請求案例
export const login = (query) => {
return apiResquest({
url: '這里是API的地址',
method: 'POST',
query: {...query}
})
}
//GET 請求案例可以傳遞參數(shù)也可以不傳遞
export const validateCode = (query) => {
let str = query
return apiResquest({
url: `您的API地址 ?${str}`,
method: 'GET'
})
}第四步、頁面中調用
import { login } from '../../models/index.js'
//頁面中的 methods 里面就可以直接調用了
Login(){
//這里可以設置需要傳遞的參數(shù)
let uid = uni.getStorageSync('userId')
login(uid).then((res) => {
console.log(res)
}).catch(err => {
console.log(err)
})
}以上代碼就是完整的接口封裝了,真的超級實用,其實網上有很多關于uni-app接口封裝的案例,但是個人感覺親測了好幾種,這種是最好用的。分享在這里希望和大家一起交流。
總結
到此這篇關于uni-app調取接口的3種方式以及封裝uni.request()的文章就介紹到這了,更多相關uni-app調取接口及封裝uni.request()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript 判斷一個對象{}是否為空對象的簡單方法
下面小編就為大家?guī)硪黄狫avaScript 判斷一個對象{}是否為空對象的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10
JavaScript 開發(fā)中規(guī)范性的一點感想
在開發(fā)中通用的幾個方法,我們把它們放到utility目錄下或者utility.js中;所有的提示信息和報錯信息統(tǒng)一放置在一起??雌饋矶际切⌒〉膸撞?,卻能讓咱們開發(fā)的代碼同事讀起來更順暢,下個項目中也能用上。2009-06-06

