axios 用法和封装

一 基本使用

1.1 安装

  1.使用npm

    npm install axios

  2.CDN

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

1.2 基本用法 更多参考: GitHub - axios/axios: Promise based HTTP client for the browser and node.js

//给一个参数ID 
axios.get("url?ID=12345").then(
  function(result){//成功回调
    console.log(result)
}).catch(function (error) {//失败回调
    console.log(error);
}).then(function () {
    //总是执行  -- catch里面也会返回一个新的 promise
})

//上面的请求也可选择下面的方式来写
axios.get('url',{ params:{ ID:12345 } }).then(
  function(response){
    console.log(response);
}).catch(function(error){
    console.log(error)
});

//可以通过将相关配置传递给 axios 来进行请求
// 发送一个 POST 请求
axios({
  method: 'post',
  url: 'url',
  data: {
    ID:12345
   }
});

1.3 举个栗子

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  //全局配置
  axios.defaults.baseURL = "http://192.168.0.112/vuetest/lib/"
  //发起get请求
  axios.get("http-test.php").then(
    function (result) {//成功回调
      console.log(result)
    }).catch(function (error) {//失败回调
      console.log(error);
    })

  //发起post请求
  axios.post("http-test.php", { ID: 12345 }).then(
    function (result) {//成功回调
      console.log(result)
    }).catch(function (error) {//失败回调
      console.log(error)
    })

  //发起多重并发请求
  axios.all([
    axios.get('http-test.php'),
    axios.get('http-test2.php')
  ]).then(
    axios.spread(function (resource, resource2) {
      //两个请求都完成
      console.log(resource.data)
      console.log(resource2.data)
    })
  ).catch(function (err) {
    console.log(err)
  })

</script>

二 vue中Axios的封装

2.1 新建 axios/index.js

import axios from 'axios'

const instance = axios.create({
    baseURL: "http://192.168.0.000",
    timeout: 1000 * 30, // 所有接口30s超时
    withCredentials: false,
    //withCredentials: true, 跨域请求时是否需要使用凭证,为 true 时必须在后端设置Access-Control-Allow-Origin 字段必须指定域名,不能为*
    // headers: {
    //     'Content-Type': 'application/json; charset=utf-8'
    // }
})

// 请求统一处理
instance.interceptors.request.use(
    async (config) => {
        // 添加token
        // if(store.token){
        //     config.headers['test-token'] = store.token
        // }
        return config
    },
    (error) => Promise.reject(error)
)

// 对返回的内容做统一处理
instance.interceptors.response.use(
    (response) => {
        if (response.status === 200) {
            return response
        }
        return Promise.reject(response)
    },
    (error) => {
        if (error) {
            console.log(JSON.stringify(error))
        } else {
            console.log('出了点问题,暂时加载不出来,请稍后再来吧')
        }
        return Promise.reject(error)
    }
)

export default instance

2.2 main.js  全局注册,之后可在其他组件中通过 this.$http 发送数据

import axios from './axios/index'
Vue.prototype.$http = axios

2.3 组件中使用

this.$http.post("/RUL",{
  username: "username"
}).then(function(res){
  console.log(res)
})

三 坑坑坑坑坑

 3.1 正常调 post 后台无法获取参数  如下

this.$http.post("/test.php", {username: "tom",password: "123"}).then(function(res){
  console.log(res.data)
})

解决方法有两种

import qs from "qs"; //需要安装 npm install qs 
var params = qs.stringify({username: "tom",password: "123"})
this.$http.post("/test.php", params)  //params = "username=tom&password=123"

var params = new URLSearchParams();
params.append('username', "tom");
params.append('password', "123");
this.$http.post("/test.php", params) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值