龙空技术网

Post请求Loading及封装

青少年编程ABC 283

前言:

现时看官们对“node post请求”可能比较关心,朋友们都需要学习一些“node post请求”的相关文章。那么小编在网络上搜集了一些关于“node post请求””的相关内容,希望小伙伴们能喜欢,各位老铁们快快来了解一下吧!

Post请求Loading及封装1.组件axiossweetalert2.目标

对post请求进行封装的目标及最终实现如下:

实现在请求时弹出遮罩层在header中设置Authorization发生错误弹出错误提示信息鉴权失败后跳转到登录页面3.loading代码

使用 JS 代码实现在页面上显示遮罩层及图片,代码如下:

/* * GUID */function guid () {  function S4 () {    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)  }  return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())}/* * 显示loading遮罩层 */function loading () {  var id = guid()  var maskBg = document.createElement('div')  maskBg.id = 'mask_bg_' + id  maskBg.style.position = 'absolute'  maskBg.style.top = '0px'  maskBg.style.left = '0px'  maskBg.style.width = '100%'  maskBg.style.height = '100%'  maskBg.style.backgroundColor = '#777'  maskBg.style.opacity = 0.6  maskBg.style.zIndex = 10001  document.body.appendChild(maskBg)  var maskMsg = document.createElement('div')  maskMsg.style.position = 'absolute'  maskMsg.style.top = '43%'  maskMsg.style.left = '43%'  maskMsg.style.textAlign = 'center'  maskMsg.style.zIndex = 10002  var image = document.createElement('img')  image.src = '/images/rotate_loader.svg' // 加载图片  maskMsg.appendChild(image)  maskBg.appendChild(maskMsg)  return maskBg.id}/* * 关闭遮罩层 */function loaded (id) {  var maskBg = document.getElementById(id)  if (maskBg != null) {    maskBg.parentNode.removeChild(maskBg)  }}export {loading, loaded}
4.post请求封装

代码如下:

import axios from 'axios'import swal from 'sweetalert'import {loading, loaded} from './loading'const config = {  baseURL: '',  timeout: 60000,  headers: {    'Content-Type': 'application/json'  },  responseType: 'json'}const postRequest = (url, data) => {  let _id = loading()  // eslint-disable-next-line  const promise = new Promise((resolve, reject) => {    // 设置Headers的Authorization,鉴权Token    config.headers['Authorization'] =        localStorage.getItem('token_type') + ' ' + localStorage.getItem('access_token')    axios.post(      url, data, config    ).then((response) => {      loaded(_id)      resolve(response)    }).catch((error) => {      loaded(_id)      console.log(error)      let status = error.response.status      swal(status.toString(), error.message, 'error')      if (status === 401) {        swal({          title: '鉴权失败',          text: error.message,          icon: 'error',          button: "确定",        }).then((value) => {          console.log(value)          // 路由跳转        })      }      // reject(error)    })  })  return promise}
5.Vue中使用
import {postRequest} from "@/assets/utils/utils"let _this = thispostRequest(    'url',  // url    data // Object).then((response) => {    ......})

标签: #node post请求