vue2.0/vue3.0/vue4.0之axios封装以及axios跨域

本想使用axios,但不封装的话,使用起来太臃肿,此封装方式是根据别人封装格式改造过来使用,地址在最下面。

1.axios安装:

npm install axios -D

2.封装axios,index.js

/** 接口调用工具*/
 
import axios from 'axios'  引用axios
// 配置API接口地址
var root = 'http://localhost:7002'
axios.defaults.headers.post['content-Type'] = 'application/json;charset=UTF-8';
 
// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
/** 参数过滤函数*/
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/**添加headers,可以动态添加header参数*/
function setHeaders(headers){
  axios.defaults.headers.school_id = headers.school_id;
  axios.defaults.headers.token = headers.token;
}
 
 
//其实success与failure这两个参数,传过来的是两个放方法
function apiAxios (method, url,headers, params, success, failure) {
  if (headers){
    headers = filterNull(headers);
    setHeaders(headers)
  }
 
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: root,
    withCredentials: false
  })
    .then(function (res) {
      if (res.data.error_code === 1000) {
        if (success) {
		//使用success(data)方法
          success(res.data)
        }
      } else {
        failure(res.data)
      }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        window.alert('api error, HTTP CODE: ' + res.status)
      }
    })
}
 
// 返回在vue模板中的调用接口
export default {
  get: function (url,headers, params, success, failure) {
    return apiAxios('GET', url,headers, params, success, failure)
  },
  post: function (url,headers, params, success, failure) {
    return apiAxios('POST', url,headers, params, success, failure)
  },
  put: function (url,headers, params, success, failure) {
    return apiAxios('PUT', url,headers, params, success, failure)
  },
  delete: function (url,headers, params, success, failure) {
    return apiAxios('DELETE', url,headers, params, success, failure)
  }
}

3.在main.js全局引用封装的axios js

import api from './api/index.js';
 
Vue.prototype.$api = api

4.使用例子,get请求与post请求

//get请求
this.$api.get(
   '/devices',                           //url
   {"school_id":schoolId,"token":null},  //headers
   null,                                 //params
  successRes => {                        //success(data)方法
   console.log(successRes)
  },
  failureRes =>{                        //failure(data)方法
	 console.log(failureRes)
  }
)
 
//post请求
this.$api.post(
   '/device', 
   {"school_id":schoolId,"token":null},
   {"name": "test","operator_name": "xichuan"}, 
   successRes => {                        
   console.log(successRes)
  },
  failureRes =>{                        
	 console.log(failureRes)
  }
})

5.get请求可以用下面格式

//将上面的查分开来,这样更好理解,可以看出,最后两个参数其实传递的是两个方法,一个处理success,一个处理failure
var success = function myfun(res){
     console.log(res)
}
var failure = function myfun(res){
     console.log(res)
}
this.$api.get(
   '/devices',                           //url
   {"school_id":schoolId,"token":null},  //headers
   null,                                 //params
  success(res),                        //success(data)方法
  failure(res)                        //failure(data)方法
)

跨域待更新…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Axios是一个基于Promise的HTTP客户端,可以用于浏览器和Node.js。Vue中使用Axios可以方便地进行HTTP请求。在Vue中使用Axios进行请求,可以通过以下两种方式解决: 1. 在Vue中进行配置 可以在Vue的配置文件中设置Axios的默认配置,包括请求的相关配置。具体步骤如下: ① 安装Axios ```shell npm install axios --save ``` ② 在main.js中引入Axios并进行配置 ```javascript import axios from 'axios' // 设置Axios的默认配置 axios.defaults.baseURL = 'http://localhost:8080' // 设置请求的基础URL axios.defaults.timeout = 5000 // 设置请求超时时间 // 设置Axios请求相关配置 axios.defaults.withCredentials = true // 允许携带cookie axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' // 设置POST请求的请求头 // 将Axios挂载到Vue的原型上,方便在组件中使用 Vue.prototype.$axios = axios ``` ③ 在组件中使用Axios进行请求 ```javascript this.$axios.get('/api/user', { params: { id: 1 } }).then(res => { console.log(res.data) }).catch(err => { console.log(err) }) ``` 2. 使用Nginx转发 可以使用Nginx作为反向代理服务器,将Vue的请求转发到后端服务器上,从而实现请求。具体步骤如下: ① 安装Nginx ```shell sudo apt-get install nginx ``` ② 配置Nginx 在Nginx的配置文件中添加以下内容: ```nginx server { listen 80; server_name localhost; location /api { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } ``` 其中,`/api`是Vue的请求路径,`http://localhost:8080`是后端服务器的地址。 ③ 在组件中使用Axios进行请求 ```javascript this.$axios.get('/api/user', { params: { id: 1 } }).then(res => { console.log(res.data) }).catch(err => { console.log(err) }) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值