关于vue.js:Vue-Axios请求随笔

Axios 是一个基于 promise 的 HTTP 库,能够用在浏览器和 node.js 中。

### Axios个性

1.从浏览器中创立 XMLHttpRequests

2. 从 node.js 创立 http 申请
3. 反对 Promise API
4. 拦挡申请和响应
5. 转换申请数据和响应数据
6. 勾销申请
7. 主动转换 JSON 数据
8. 客户端反对进攻 XSRF

装置

npm install axios -S

  1. 全局援用
import axios from 'axios'   
Vue.prototype.$axios = axios
//子组件 mounted生命周期函数中应用 
this.$axios.get("http://xx")
.then(res=>{console.log(res)})
.catch(error=>{console.log(error)})
  1. 部分援用
import $axios from 'axios'
//组件 mounted生命周期函数中应用 
$axios.get("http://xx").then(res=>{console.log(res)})
//第二种书写格局 :
$axios.get("http://iwenwiki.com/api/music/list.php",{
        params:{
                   type:1,
                   count:10,
                offset:0
            }
    }).then(res=>{
    console.log(res)
    })
  1. 也能够通过向axios传递相干配置这种办法来创立申请
$axios({
     method:'post',
      url:"http://iwenwiki.com/api/blueberrypai/login.php",
      data:qs.stringify({
            user_id:"iwen@qq.com",
              password:"iwen123",
              verification_code:"crfvw"
      })
}).then(...)

申请配置选项
这些是创立申请时能够用的配置选项。只有 url 是必须的。如果没有指定 method,申请将默认应用 get 办法。

{
    url       //url是用于申请的服务器 URL
    method      //method` 是创立申请时应用的办法
    baseURL     //将主动加在 `url` 后面,除非url是一个相对URL
    transformRequest: [function (data, headers) { //容许在向服务器发送前,批改申请数据
                return data;    // 对 data 进行任意转换解决
      }],
    transformResponse: [function (data) { //在传递给 then/catch 前,容许批改响应数据
               return data;// 对 data 进行任意转换解决
      }],
    headers    //是行将被发送的自定义申请头
    params: {     //是行将与申请一起发送的 URL 参数
                ID: 12345
      },
     data: {
                firstName: 'Fred'
      },    
    timeout: 1000,
    responseType: 'json',
      //查看文档http://www.axios-js.com/zh-cn/docs/#axios-API还有很多
           }

响应构造
申请的响应蕴含以下信息 :
data{ } , status , statusText , headers , config , request

  1. 为了不便,给所有申请办法起了别名

在应用别名办法时, url、method、data 这些属性都不用在配置中指定。

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

申请形式 Get / Post

  1. Get 申请 : $axios.get(“http://xx”).then()
  2. Post申请 :须要用querystring把传参的对象模式转换成字符串,因为axios承受的参数是一个字符串类型
 import qs from 'query-string'
  $axios.post("http://xx",qs.stringify({
                user_id:"iwen@qq.com",
            password:"iwen123",
              verification_code:"crfvw"
          })).then()

执行多个并发申请

用到的解决并发申请的助手函数:
axios.all(iterable) 和 axios.spread(callback)

function AA(){
         return     $axios.get("http://xx") //这里不加.then()
    }
function BB(){
         return     $axios.get2/post("http://xxx");
    }
    
$axios.all([AA(),BB()])
.then($axios.spread((AA,BB)=>{console.log(AA,BB)}))

自定义创立实例

const instance = axios.create({
            baseURL : "http://xxx",
            timeout : 1000,
            headers : {'X-Custom-Header': 'foobar'}
    })

配置默认值【重点】

全局的 axios 默认值
axios.defaults.baseURL = ‘https://api.example.com’;
axios.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;

拦截器

在申请或响应被 then 或 catch 解决前拦挡它们。

  1. 增加申请拦截器
axios.interceptors.request.use(function (config) {
        // 在发送申请之前做些什么
             // 配置
            if(config.method === 'post'){
                    config.data = qs.stringify(config.data);
            }
                return config;
           }, function (error) {
                   // 对申请谬误做些什么
                 return Promise.reject(error);
          });
  1. 增加响应拦截器
axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
         return response.status === 200 ? Promise.resolve(response) : Promise.reject(response),
      }, function (error) {
         // 对响应谬误做点什么
         return Promise.reject(error);
      });

想在稍后移除拦截器,能够这样:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

跨域解决

  1. 开发环境跨域解决方案 : Proxy代理(只在开发环境下应用无效。

    应用场景:
       1.后盾开发者没有工夫解决跨域问题  
       2.本人模仿数据服务器,例如mock产生跨域)
       

    第一步 :在我的项目根目录下创立配置文件 vue.config.js ,而后配置该文件,每次批改完该文件必须从新启动我的项目

module.exports = {
    devServer:{
        proxy:{
            "api":{
                target:"http://iwenwiki.com",  //代理申请地址
                pathRewrite:{  //重写门路
                    "^/api":"/api/FingerUnion"; //地址
                    },
                changeOrigin:true  //容许跨域
            }
        }
    }
}

第二步 :在api文件下的base.js(存储门路)中增加配置proxyURL : “/api”

const base = {
                baseURL:"http://iwenwiki.com",
                proxyURL:"/api",
                     banner:"/api/blueberrypai/getIndexBanner.php",
                list:"/list.php",
        }
export default base;

第三步 :在api文件下的index.js(封装申请)中封装申请数据

import base from './base'
import axios from '../utils/request'

const api = {
        getBanner(){
            return axios.get(base.baseURL+base.banner)
        },
        getList(params){
            return axios.get(base.proxyURL+base.list,{
                    params:params
                })
        }
}

export default api;

第四步 :将api文件引入到全局main.js中或者任意组件中 import api from ‘./api’ ,如果是引入到全局中则须要将api挂载到Vue原型上(Vue.prototype.$api = api;),而后调用api中的封装的网络申请函数

this.$api.getList({    //此例子将api引入到全局
          page:1
        }).then(res=>{
          console.log(res.data);
})
  1. 开发环境跨域解决方案 : CORS后盾解决跨域

生产环境跨域解决方案 : CORS后盾解决跨域

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理