欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue实现的请求服务器端API接口示例

程序员文章站 2023-12-04 22:16:34
本文实例讲述了vue实现的请求服务器端api接口。分享给大家供大家参考,具体如下: import axios from 'axios' import route...

本文实例讲述了vue实现的请求服务器端api接口。分享给大家供大家参考,具体如下:

import axios from 'axios'
import router from '@/router'
axios.defaults.timeout = 3000
axios.defaults.baseurl = ''
axios.interceptors.request.use(
 config => {
  // const token = getcookie('名称')
  config.data = config.data
  config.headers = {
   'content-type': 'application/json; charset=utf-8'
  }
  if (config.url === '/api/login/index') {
  } else {
   if (localstorage.getitem('authorization')) {
    config.headers.authorizatior = localstorage.getitem('authorization')
   }
  }
  // if (token) {
  // config.params = {'token': token}
  // }
  return config
 },
 error => {
  return promise.reject(error)
 }
)
axios.interceptors.response.use(
 response => {
  //返回错误跳转到首页
  if (response.data.code === 0) {
   router.push({
    path: '/',
    querry: {
     redirect: router.currentroute.fullpath
    }
   })
  }
  return response
 },
 error => {
  if (error.response) {
   switch (error.response.status) {
    case 401:
     localstorage.removeitem('authorization')
     router.push('/login')
   }
  }
  return promise.reject(error)
 }
)
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {promise}
 */
export function fetch (url, params = {}) {
 return new promise((resolve, reject) => {
  axios.get(url, {
   params: params
  })
  .then(response => {
   resolve(response.data)
  })
  .catch(err => {
   reject(err)
  })
 })
}
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {promise}
 */
export function post (url, data = {}) {
 return new promise((resolve, reject) => {
  axios.post(url, data)
  .then(response => {
   resolve(response.data)
  }, err => {
   reject(err)
  })
 })
}
/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {promise}
 */
export function patch (url, data = {}) {
 return new promise((resolve, reject) => {
  axios.patch(url, data)
   .then(response => {
    resolve(response.data)
   }, err => {
    reject(err)
   })
 })
}
/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {promise}
 */
export function put (url, data = {}) {
 return new promise((resolve, reject) => {
  axios.put(url, data)
   .then(response => {
    resolve(response.data)
   }, err => {
    reject(err)
   })
 })
}

main.js调用

import { fetch, post, patch, put } from '@/util/fetch'
vue.prototype.get = fetch
vue.prototype.post = post
vue.prototype.patch = patch
vue.prototype.put = put

视图页面使用 

export default {
 name: 'login',
 data () {
  return {
   mobile: '',
   password: ''
  }
 },
 components: {
  xinput,
  xbutton,
  group,
  box
 },
 methods: {
  handlelogin () {
   let params = {}
   params.username = this.mobile
   params.password = this.password
   this.post('/api/driver/index', params).then((data) => {
    console.log(data)
   }).catch((error) => {
    console.log(error)
   })
  }
 }
}

希望本文所述对大家vue.js程序设计有所帮助。