Vue之axios网络请求
发送网络请求的方式
- 传统ajax(基于XHR,XMLHttpRequest)
- 配置、调用方式等较混乱
- 较少使用(真实开发一般使用JQuery-Ajax)
- JQuery-Ajax
- 比传统ajax好用一些
- 一般Vue项目开发不需要使用JQuery
- Vue-resource(基于Vue1.0)
- 体积小于JQuery
- Vue2.0推出之后,不再继续维护、更新Vue-resource
- axios框架
- 浏览器中发送XHR请求
- 在node.js中发送http请求
- 支持Promise
- 拦截请求和响应
- 转换请求和响应数据
- ……
axios请求方式与基础使用
请求方式
axios(config)
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
基础使用(以get请求为例)
安装axios
在终端输入命令npm install axios --save
安装成功
get请求
无请求参数
代码:
<script>
import axios from 'axios'
export default {
name: "getReq",
created() {
// 无请求参数
axios.get('http://123.207.32.32:8000/category')
.then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
}
</script>
效果:
配置信息
数据信息
有请求参数
代码:
<script>
import axios from 'axios'
export default {
name: "getReq",
created() {
// 有请求参数
axios.get('http://123.207.32.32:8000/home/data', {
params: {
type: 'sell',
page: 1
}
})
.then(res => {
console.log(res)
}).catch(err => {
console.log(err);
})
}
}
</script>
效果:
并发请求
- 使用axios.all,可以放入多个请求的数组。
- axios.all([]) 返回的结果是一个数组
- 使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2
代码:
<script>
import axios from 'axios'
export default {
name: "getReq",
created() {
// 并发请求
axios.all([
axios.get('http://123.207.32.32:8000/category'),
axios.get('http://123.207.32.32:8000/home/data', {
params: {
type: 'sell',
page: 1
}
})
]).then(axios.spread((res1, res2) => {
console.log(res1);
console.log(res2);
}))
}
}
</script>
效果:
全局配置
- baseURL
如:axios.defaults.baseURL = ‘地址’ - headers
如:axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’
配置选项
- 请求地址
如:url: ‘/user’, - 请求类型:get、post、head、put、delete、options、trace、connect
如:method: ‘get/post/……’ - 请根路径
如:baseURL: ‘http://www.mt.com/api’ - 请求前的数据处理
如:transformRequest:[function(data){}] - 请求后的数据处理
如:transformResponse: [function(data){}] - 自定义的请求头
如:headers:{‘x-Requested-With’:‘XMLHttpRequest’} - URL查询对象
如:params:{ id: 12 } - 查询对象序列化函数
paramsSerializer: function(params){ } - 请求体(request body)
data: { key: ‘aa’} - 超时设置(毫秒)
如:timeout: 1000 - 跨域是否带Token
如:withCredentials: false - 自定义请求处理
如:adapter: function(resolve, reject, config){} - 身份验证信息
如:auth: { uname: ‘’, pwd: ‘12’} - 响应的数据格式 json、blob、document、arraybuffer、text、stream
如:responseType: ‘json’
基本使用
创建axios实例
当我们从axios模块中导入对象时, 使用的实例是默认的实例(已经设置一些固定的配置)但后续开发中, 某些可能会改变某些配置,如:某些请求需要使用特定的baseURL或timeout或content-Type等,就需要创建新的axios实例, 并且传入属于该实例的配置信息。
……
// axios实例
const axiosInstance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
……
通过axios实例发送请求
代码:
axiosInstance({
url: '/category',
method: 'get'
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
效果:
axios之拦截器
axios提供了拦截器,用于每次发送请求或者得到响应后,进行相应的处理。
拦截器的基本使用
代码:
// axios实例
const axiosInstance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
// 配置请求拦截
// 请求成功或失败
axiosInstance.interceptors.request.use(config => {
console.log('request拦截seccess中')
return config
}, err => {
console.log('request拦截failure中')
return err
})
// 配置响应拦截
// 响应成功或失败
axiosInstance.interceptors.response.use(resp => {
console.log('response拦截success中')
return resp.data
}, err => {
console.log('response拦截failure中')
return err
})
axiosInstance({
url: '/home/data',
method: 'get',
params: {
type: 'sell',
page: 1
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
效果:
请求拦截主要用途
-
成功拦截中
- 发送网络请求时,在页面中添加一个loading组件,作为动画加载效果
- 发送某些请求(如:要求用户必须登录的等),判断用户是否有token。若没有,则跳转到login页面,反之发送请求
- 对请求的参数进行序列化
-
错误拦截中
- 配置相关的拦截。如:请求超时,则跳转到404等错误页面
响应拦截主要用途
-
成功拦截中
- 主要是对数据进行过滤。
-
错误拦截中
- 可以根据status判断报错的错误码,跳转到不同的错误提示页面。
如:400语法问题,401访问拒绝,403请求被禁止……
- 可以根据status判断报错的错误码,跳转到不同的错误提示页面。
补充
了解Jsonp(一种常见的网络请求方式)
Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)处获取资料,即跨域读取数据。
使用Jsonp最主要的原因往往是为了解决跨域访问的问题。
Jsonp的原理
Jsonp的核心在于通过<script>标签的src来请求数据。
当项目部署在domain1.com服务器上时, 是不能直接访问domain2.com服务器上的资料的(跨域问题)。此时,可以利用<script>标签的src去服务器请求到数据,将数据当做一个javascript的函数来执行,并且执行的过程中传入需要的json。所以,封装sonp的核心就在于我们监听window上的jsonp进行回调时的名称。
如客户想访问 : https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction。
假设客户期望返回数据:[“customername1”,“customername2”]。
真正返回到客户端的数据显示为: callbackFunction([“customername1”,“customername2”])。
补充
为什么从不同的域(网站)访问数据需要一个特殊的技术( JSONP )呢?
是因为同源策略(由 Netscape 提出的一个著名的安全策略)。现在所有支持 JavaScript 的浏览器都会使用这个策略。