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后台解决跨域

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐