vue封装axios接口请求

Home.vue

<template>
  <div class="home">
    <button @click="getVeryTakeInformation">get非携参请求数据</button>
    <button @click="getTakeInformation">get携参请求数据</button>
    <button @click="postData">post携参请求数据</button>
  </div>
</template>

<script>
import { getVeryTakeJoin, getTakeJoin, postComment } from '../request'
export default {
  name: 'Home',
  components: {
  },
  methods: {
    getVeryTakeInformation () {
      getVeryTakeJoin().then(data => {
        console.log('get未携参返回数据', data)
      })
    },
    getTakeInformation () {
      const info = { basis_id: 287 }
      getTakeJoin(info).then(data => {
        console.log('get携参返回数据', data)
      })
    },
    postData () {
      const info = { id: 287, limit: 10, page: 2 }
      postComment(info).then(data => {
        console.log('post获取评论数据', data)
      })
    }
  }
}
</script>

request/index.js

import network from './network'
// 接口文件
import port from './port'

// get非携带参数请求
export function getVeryTakeJoin () {
  return network({
    url: port.userInfoPort,
    method: 'get'
  })
}
// get携带参数请求
export function getTakeJoin (info) {
  return network({
    url: port.courseInfo + `${Object.keys(info)[0]}=${info.basis_id}`,
    method: 'get'
  })
}
// post携带参数请求
export function postComment (info) {
  return network({
    url: port.comment,
    method: 'post',
    data: info
  })
}

request/network.js

import axios from 'axios'
// axios实例
const setAs = axios.create({
  baseURL: 'https://www.xxx.com',
  timeout: 5000
})

// 请求拦截
setAs.interceptors.request.use(data => {
  console.log('请求拦截', data)
  return data
// eslint-disable-next-line prefer-promise-reject-errors
}, _error => Promise.reject('请求错误'))

// 响应拦截
setAs.interceptors.response.use(data => {
  console.log('响应拦截', data)
  return data
// eslint-disable-next-line prefer-promise-reject-errors
}, _error => Promise.reject('响应错误'))

export default setAs

request/port.js

const storagePort = {
  // 获取用户信息接口
  userInfoPort: '/api/xxx/userInfo',
  // 获取课程信息接口
  courseInfo: '/api/xxx/courseInfo/',
  // 获取评论接口
  comment: '/api/xxx/courseComment'
}
// 导出携带接口对象
export default storagePort
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值