国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

uni-app 使用uni.request封裝發(fā)送api請求文檔服務器請求導航守衛(wèi)

這篇具有很好參考價值的文章主要介紹了uni-app 使用uni.request封裝發(fā)送api請求文檔服務器請求導航守衛(wèi)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言

  • 剛剛接觸uni-app時候想著直接使用axios發(fā)請求,可以發(fā)送成功但是請求頭有點問題

  • 后面發(fā)現(xiàn)教程都是使用@escookrequest-miniprogram三方包發(fā)送請求-(瀏覽器環(huán)境發(fā)送不了請求,不兼容)

  • 為什么不直接用uni.request()發(fā)送請求,是因為每次請求都要寫一次添加請求頭不合理

  • 后面隨著深入了解uni-app,發(fā)現(xiàn)開源框架,若依,芋道,都是封裝一層uni.request發(fā)請求

  • 解決了統(tǒng)一添加請求頭問題,使用uni.request比較合理,自己寫可能不全面,可以直接搬

細節(jié)

1.觀察我們會發(fā)現(xiàn)在utils工具文件夾下有upload.js和request.js2個文件在發(fā)請求是都在引入

2.request.js基于uni.request封裝添加請求頭,用戶id。專門用來發(fā)送普通api請求

3.upload.js基于 uni.uploadFile封裝添加請求頭,用戶id,專門用來對接文檔服務器,上傳圖片文件

4.并不是所有接口都需要添加請求頭,在不需要添加的請求頭的接口寫isToken: false

5.uni.request發(fā)請求是兼容瀏覽器環(huán)境的,@escookrequest-miniprogram是不兼容瀏覽器發(fā)請求

代碼實現(xiàn)

1.在utils工具文件夾下分別建立request.js和upload.js文件夾-代碼如下

request.js

// 引入vuex-調用退出登錄方法
import store from '@/store'
// 引入基地址文件
import config from '@/config'
// 引入獲取token文件
import { getAccessToken } from '@/utils/auth'
// 引入轉臺碼錯誤文件
import errorCode from '@/utils/errorCode'
// 引入公共方法文件
import { toast, showConfirm, tansParams } from '@/utils/common'
?
let timeout = 10000
const baseUrl = config.baseUrl;
?
const request = config => {
  // 是否需要設置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getAccessToken() && !isToken) {
 ?  config.header['Authorization'] = 'Bearer ' + getAccessToken()
  }
  // 設置租戶 TODO 芋艿:強制 1 先
  config.header['tenant-id'] = '1';
  // get請求映射params參數(shù)
  if (config.params) {
 ?  let url = config.url + '?' + tansParams(config.params)
 ?  url = url.slice(0, -1)
 ?  config.url = url
  }
  return new Promise((resolve, reject) => {
 ?  uni.request({
 ? ? ?  method: config.method || 'get',
 ? ? ?  timeout: config.timeout ||  timeout,
 ? ? ?  url: config.baseUrl || baseUrl + config.url,
 ? ? ?  data: config.data,
 ? ? ?  // header: config.header,
 ? ? ?  header: config.header,
 ? ? ?  dataType: 'json'
 ? ?  }).then(response => {
 ? ? ?  let [error, res] = response
 ? ? ?  if (error) {
 ? ? ? ?  toast('后端接口連接異常')
 ? ? ? ?  reject('后端接口連接異常')
 ? ? ? ?  return
 ? ? ?  }
 ? ? ?  const code = res.data.code || 200
 ? ? ?  const msg = errorCode[code] || res.data.msg || errorCode['default']
 ? ? ?  if (code === 401) {
 ? ? ? ?  showConfirm('登錄狀態(tài)已過期,您可以繼續(xù)留在該頁面,或者重新登錄?').then(res => {
 ? ? ? ? ?  if (res.confirm) {
 ? ? ? ? ? ?  store.dispatch('LogOut').then(res => {
 ? ? ? ? ? ? ?  uni.reLaunch({ url: '/pages/login' })
 ? ? ? ? ? ?  })
 ? ? ? ? ?  }
 ? ? ? ?  })
 ? ? ? ?  reject('無效的會話,或者會話已過期,請重新登錄。')
 ? ? ?  } else if (code === 500) {
 ? ? ? ?  toast(msg)
 ? ? ? ?  reject('500')
 ? ? ?  } else if (code !== 200) {
 ? ? ? ?  toast(msg)
 ? ? ? ?  reject(code)
 ? ? ?  }
 ? ? ?  resolve(res.data)
 ? ?  })
 ? ?  .catch(error => {
 ? ? ?  let { message } = error
 ? ? ?  if (message === 'Network Error') {
 ? ? ? ?  message = '后端接口連接異常'
 ? ? ?  } else if (message.includes('timeout')) {
 ? ? ? ?  message = '系統(tǒng)接口請求超時'
 ? ? ?  } else if (message.includes('Request failed with status code')) {
 ? ? ? ?  message = '系統(tǒng)接口' + message.substr(message.length - 3) + '異常'
 ? ? ?  }
 ? ? ?  toast(message)
 ? ? ?  reject(error)
 ? ?  })
  })
}
?
export default request
?

upload.js

// 引入vuex-調用退出登錄方法
import store from '@/store'
// 引入基地址文件
import config from '@/config'
// 引入獲取token文件
import { getAccessToken } from '@/utils/auth'
// 引入轉臺碼錯誤文件
import errorCode from '@/utils/errorCode'
// 引入公共方法文件
import { toast, showConfirm, tansParams } from '@/utils/common'
?
let timeout = 10000
const baseUrl = config.baseUrl
?
const upload = config => {
  // 是否需要設置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getAccessToken() && !isToken) {
 ?  config.header['Authorization'] = 'Bearer ' + getAccessToken()
  }
  // get請求映射params參數(shù)
  if (config.params) {
 ?  let url = config.url + '?' + tansParams(config.params)
 ?  url = url.slice(0, -1)
 ?  config.url = url
  }
  // 設置租戶 TODO 芋艿:強制 1 先
  config.header['tenant-id'] = '1';
  return new Promise((resolve, reject) => {
 ? ?  uni.uploadFile({
 ? ? ?  timeout: config.timeout || timeout,
 ? ? ?  url: baseUrl + config.url,
 ? ? ?  filePath: config.filePath,
 ? ? ?  name: config.name || 'file',
 ? ? ?  header: config.header,
 ? ? ?  formData: config.formData,
 ? ? ?  method: config.method || 'post',
 ? ? ?  success: (res) => {
 ? ? ? ?  let result = JSON.parse(res.data)
 ? ? ? ?  const code = result.code || 200
 ? ? ? ?  const msg = errorCode[code] || result.msg || errorCode['default']
 ? ? ? ?  if (code === 200) {
 ? ? ? ? ?  resolve(result)
 ? ? ? ?  } else if (code == 401) {
 ? ? ? ? ?  showConfirm("登錄狀態(tài)已過期,您可以繼續(xù)留在該頁面,或者重新登錄?").then(res => {
 ? ? ? ? ? ?  if (res.confirm) {
 ? ? ? ? ? ? ?  store.dispatch('LogOut').then(res => {
 ? ? ? ? ? ? ? ?  uni.reLaunch({ url: '/pages/login/login' })
 ? ? ? ? ? ? ?  })
 ? ? ? ? ? ?  }
 ? ? ? ? ?  })
 ? ? ? ? ?  reject('無效的會話,或者會話已過期,請重新登錄。')
 ? ? ? ?  } else if (code === 500) {
 ? ? ? ? ?  toast(msg)
 ? ? ? ? ?  reject('500')
 ? ? ? ?  } else if (code !== 200) {
 ? ? ? ? ?  toast(msg)
 ? ? ? ? ?  reject(code)
 ? ? ? ?  }
 ? ? ?  },
 ? ? ?  fail: (error) => {
 ? ? ? ?  let { message } = error
 ? ? ? ?  if (message == 'Network Error') {
 ? ? ? ? ?  message = '后端接口連接異常'
 ? ? ? ?  } else if (message.includes('timeout')) {
 ? ? ? ? ?  message = '系統(tǒng)接口請求超時'
 ? ? ? ?  } else if (message.includes('Request failed with status code')) {
 ? ? ? ? ?  message = '系統(tǒng)接口' + message.substr(message.length - 3) + '異常'
 ? ? ? ?  }
 ? ? ? ?  toast(message)
 ? ? ? ?  reject(error)
 ? ? ?  }
 ? ?  })
  })
}
?
export default upload
?

2.在最外層與utils.js同級下創(chuàng)建基地址文件config.js

// 應用全局配置
module.exports = {
  baseUrl: '基地址',
  // 應用信息
  appInfo: {
 ?  // 應用名稱
 ?  name: "app",
 ?  // 應用版本
 ?  version: "1.0.0",
 ?  // 應用logo
 ?  logo: "/static/logo.png",
 ?  // 官方網站
 ?  site_url: "",
 ?  // 政策協(xié)議
 ?  agreements: [{
 ? ? ?  title: "隱私政策",
 ? ? ?  url: ""
 ? ?  },
 ? ?  {
 ? ? ?  title: "用戶服務協(xié)議",
 ? ? ?  url: ""
 ? ?  }
 ?  ]
  }
}
?

3.在utils.js工具文件下創(chuàng)建auth.js文件-存儲token

RefreshTokenKey-是用來補救token失效換取token的一種無感刷新形式沒有不用管

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'
?
// ========== Token 相關 ==========
?
export function getAccessToken() {
  return uni.getStorageSync(AccessTokenKey)
}
?
export function getRefreshToken() {
  return uni.getStorageSync(RefreshTokenKey)
}
?
export function setToken(token) {
  uni.setStorageSync(AccessTokenKey, token.accessToken)
  uni.setStorageSync(RefreshTokenKey, token.refreshToken)
}
?
export function removeToken() {
  uni.removeStorageSync(AccessTokenKey)
  uni.removeStorageSync(RefreshTokenKey)
}
?

4.在utils.js工具文件下創(chuàng)建errorCode.js文件-狀態(tài)碼錯誤文件

export default {
  '401': '認證失敗,無法訪問系統(tǒng)資源',
  '403': '當前操作沒有權限',
  '404': '訪問資源不存在',
  'default': '系統(tǒng)未知錯誤,請反饋給管理員'
}
?

5.在utils.js工具文件下創(chuàng)建common.js文件-公共方法

/**
* 顯示消息提示框
* @param content 提示的標題
*/
export function toast(content) {
  uni.showToast({
 ?  icon: 'none',
 ?  title: content
  })
}
?
/**
* 顯示模態(tài)彈窗
* @param content 提示的標題
*/
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
 ?  uni.showModal({
 ? ?  title: '提示',
 ? ?  content: content,
 ? ?  cancelText: '取消',
 ? ?  confirmText: '確定',
 ? ?  success: function(res) {
 ? ? ?  resolve(res)
 ? ?  }
 ?  })
  })
}
?
/**
* 參數(shù)處理
* @param params 參數(shù)
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
 ?  const value = params[propName]
 ?  var part = encodeURIComponent(propName) + "="
 ?  if (value !== null && value !== "" && typeof (value) !== "undefined") {
 ? ?  if (typeof value === 'object') {
 ? ? ?  for (const key of Object.keys(value)) {
 ? ? ? ?  if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
 ? ? ? ? ?  let params = propName + '[' + key + ']'
 ? ? ? ? ?  var subPart = encodeURIComponent(params) + "="
 ? ? ? ? ?  result += subPart + encodeURIComponent(value[key]) + "&"
 ? ? ? ?  }
 ? ? ?  }
 ? ?  } else {
 ? ? ?  result += part + encodeURIComponent(value) + "&"
 ? ?  }
 ?  }
  }
  return result
}

5.在utils.js工具文件下創(chuàng)建permission.js文件-導航守衛(wèi)設置白名單,頁面攔截器

import { getAccessToken } from '@/utils/auth'
?
// 登錄頁面
const loginPage = "/pages/login"
?
// 頁面白名單
const whiteList = [
  '/pages/login', '/pages/common/webview/index'
]
?
// 檢查地址白名單
function checkWhite(url) {
  const path = url.split('?')[0]
  return whiteList.indexOf(path) !== -1
}
?
// 頁面跳轉驗證攔截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
list.forEach(item => {
  uni.addInterceptor(item, {
 ?  invoke(to) {
 ? ?  if (getAccessToken()) {
 ? ? ?  if (to.path === loginPage) {
 ? ? ? ?  uni.reLaunch({ url: "/" })
 ? ? ?  }
 ? ? ?  return true
 ? ?  } else {
 ? ? ?  if (checkWhite(to.url)) {
 ? ? ? ?  return true
 ? ? ?  }
 ? ? ?  uni.reLaunch({ url: loginPage })
 ? ? ?  return false
 ? ?  }
 ?  },
 ?  fail(err) {
 ? ?  console.log(err)
 ?  }
  })
})
?

6.在main.js中引入導航守衛(wèi)文件

// permission
// 導航守衛(wèi)文件
import './permission' 

7.發(fā)送請求例子

// 對接文檔服務器封裝
import upload from '@/utils/upload'
// 對接普通api接口
import request from '@/utils/request'
?
// 登錄方法-不需要添加token-請求頭添加isToken: false
export function login(username, password, captchaVerification) {
    const data = {
        username,
        password,
        captchaVerification
    }
    return request({
        url: '/system/auth/login',
        headers: {
            isToken: false
        },
        'method': 'POST',
        'data': data
    })
}
?
// 查詢用戶個人信息-普通api添加token+用戶id
export function getUserProfile() {
  return request({
 ?  url: '/system/user/profile/get',
 ?  method: 'GET'
  })
}
?
// 用戶頭像上傳-對接文檔服務器
export function uploadAvatar(data) {
  return upload({
 ?  url: '/system/user/profile/update-avatar',
 ?  method: 'PUT',
 ?  name: data.name,
 ?  filePath: data.filePath
  })
}

總結:

經過這一趟流程下來相信你也對 uni-app 使用uni.request封裝發(fā)送api請求文檔服務器請求導航守衛(wèi) 有了初步的深刻印象,但在實際開發(fā)中我 們遇到的情況肯定是不一樣的,所以我們要理解它的原理,萬變不離其宗。加油,打工人!

什么不足的地方請大家指出謝謝 -- 風過無痕文章來源地址http://www.zghlxwxcb.cn/news/detail-603339.html

到了這里,關于uni-app 使用uni.request封裝發(fā)送api請求文檔服務器請求導航守衛(wèi)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • uni-app:請求后端數(shù)據(jù)uni.request

    uni-app:請求后端數(shù)據(jù)uni.request

    ?完整代碼: 核心 使用的方法 uni.request({...}); ?與接口相連接的路徑 注:這里標紅的部分為全局變量 例如: url:\\\'https://域名/api/Produce/select_employee\\\'(表示在使用該域名下的api中的Produce文件的select_employee方法) url: getApp().globalData.position + \\\'Produce/select_employee\\\', 傳入數(shù)據(jù)到后端?

    2024年02月16日
    瀏覽(31)
  • uni-app項目封裝http請求和不封裝請求

    在頁面文件中 該請求的封裝方式適用于_gt、_mt類型的請求,應該也可以做到其他類型; 注意看代碼中的注釋 在uilt/api.js中 在uilt/http.js中 在頁面文件中 注意看代碼中的注釋;不封裝需要使用 uni.request這個API來進行請求

    2024年02月13日
    瀏覽(27)
  • uni-app中調取接口的三種方式與封裝uni.request()

    1、uni.request({}) 2、uni.request({}).then() 3、async/await 1、創(chuàng)建一個對象,將該對象掛在Vue的原型下 新建 @/common/request.js 文件 初步寫法(僅供參考): 二次更改: 2、進入main.js文件 例:在任意文件中書寫下列代碼可以調用。 this.$Z.get(); 3、在頁面中調用 uniapp的網絡請求方法 CODE u

    2024年02月09日
    瀏覽(23)
  • [uni-app]使用uni開發(fā)微信小程序,請求接口 報錯:[“errno“:600002,errMsg“.“request;failurlnot in domain list”

    [uni-app]使用uni開發(fā)微信小程序,請求接口 報錯:[“errno“:600002,errMsg“.“request;failurlnot in domain list”

    今天練習使用uni-app開發(fā)微信小程序 知道了微信小程序請求路徑必須得是https協(xié)議 在開發(fā)過程中發(fā)現(xiàn)一個問題就是 在本地調試的時候可以正常請求request,但是發(fā)布了體驗版后就沒法請求,并且返回的是 從字面意思來講是這個請求的url的域名沒有在允許的域名列表 那么就要配

    2024年02月16日
    瀏覽(18)
  • 詳細教程 - 從零開發(fā) Vue 鴻蒙harmonyOS應用 第五節(jié) (基于uni-app封裝鴻蒙接口請求庫)

    詳細教程 - 從零開發(fā) Vue 鴻蒙harmonyOS應用 第五節(jié) (基于uni-app封裝鴻蒙接口請求庫)

    ??隨著鴻蒙系統(tǒng)的興起,越來越多的app會采用鴻蒙開發(fā)。而鴻蒙開發(fā)必不可少的就是調用各種接口服務。為了簡化接口的調用流程,我們通常會做一層封裝。今天就來講解一下,如何用uni-app封裝鴻蒙的接口請求庫。 ??首先我們要新建一個鴻蒙項目啦!當然選擇第一個空白項

    2024年02月02日
    瀏覽(26)
  • uni-app導入@escook/request-miniprogram 請求接口報錯TypeError: Cannot read property ‘get‘ of undefined

    在跟著視頻做項目的時候,突然遇到一個很奇怪的問題,正確跟著老師安裝、導包后,在使用接口請求數(shù)據(jù)時居然說‘get’未定義,經過查找發(fā)現(xiàn),只需要把導入的包,以及導包后的操作放到文件最頂部即可,如下:

    2024年02月12日
    瀏覽(48)
  • 【App端】uni-app使用echarts和百度地圖api

    【App端】uni-app使用echarts和百度地圖api

    近期的app項目中想加一個功能,展示全國各地的某一數(shù)據(jù)統(tǒng)計情況,想來想去,用echarts做地圖數(shù)據(jù)可視化直觀且美觀。于是就去研究了如何使用,其實在移動端使用echarts地圖踩的bug挺多的,總結如下。 JavaScript API GL賬號和獲取密鑰 1、獲取SHA1:Android平臺云端打包 - 公共測試

    2024年02月11日
    瀏覽(88)
  • uni-app 使用v-model封裝picker組件和自定義樣式

    1、v-model封裝picker組件 (1)封裝組件myPicker.vue (2)組件調用 (3)屬性說明 屬性名 類型 默認值 說明 options Object 數(shù)據(jù)選項,默認[{ name: \\\"辦公\\\", value: \\\"1\\\" }]格式 rangeKey String label 數(shù)據(jù)選項的屬性名 rangeValue String value 數(shù)據(jù)選項的屬性值 placeholoder String 請選擇 未選擇數(shù)據(jù)時的默認

    2024年02月09日
    瀏覽(29)
  • 【App端】uni-app使用百度地圖api和echarts省市地圖下鉆

    【App端】uni-app使用百度地圖api和echarts省市地圖下鉆

    近期的app項目中想加一個功能,展示全國各地的某一數(shù)據(jù)統(tǒng)計情況,想來想去,用echarts做地圖數(shù)據(jù)可視化直觀且美觀。于是就去研究了如何使用,其實在移動端使用echarts地圖踩的bug挺多的,總結如下。 JavaScript API GL賬號和獲取密鑰 1、獲取SHA1:Android平臺云端打包 - 公共測試

    2024年02月11日
    瀏覽(92)
  • 使用uni-app+uview創(chuàng)建小程序工程并支持請求后端接口

    使用uni-app+uview創(chuàng)建小程序工程并支持請求后端接口

    一、使用工具: ? ? 1.hubilderx? ?下載地址:HBuilderX-高效極客技巧 ? ? 2.微信開發(fā)者工具? ?下載地址:微信開發(fā)者工具下載地址與更新日志 | 微信開放文檔 ? ? 3.uview組件庫API:Color 色彩 | uView 2.0 - 全面兼容nvue的uni-app生態(tài)框架 - uni-app UI框架 二、使用hubuilderx創(chuàng)建uni-app項目

    2024年02月11日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包