Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
在 vue 官网推荐使用的是 axios 请求,所以我们可以在 vue 中使用 axios 创建 XML HttpRequests
请求,当然 axios 能做到的肯定不仅仅只是这些,在 axios 官网中介绍它具有八大特新。
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios({
url, //请求的地址
method, //请求方法 get post delete put
data, //post请求的数据
params:, //get请求的数据
headers: //请求头的配置
})
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
在使用便捷方法时, 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]])
axios.get("/api/feed?current=" + this.current).then(res => {
console.log("成功", res.data.pagnation);
this.feedList = res.data.data
this.pagnation = res.data.pagnation
console.log(res.data.pagnation.pageTotal);
}).catch(err => {
console.log(err);
})
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {},
// 'request'
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
使用 then 时,你将接收下面这样的响应 :
axios.get('/user/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
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';
在vue中配置全局默认值
// 导入axios
import axios from 'axios'
// 挂载在vue全局 每个组件都可用 prototype固定写法 $axios自定义
Vue.prototype.$axios = axios;
// 指定默认请求域名
axios.defaults.baseURL = "http://dida100.com:8888"
// 给每个请求拦截一下 添加token信息
axios.interceptors.request.use(function(config) {
config.headers.Authorization = 'Bearer ' + localStorage.getItem("token")
return config
})
// interceptors 拦截器
// config 配置
// Authorization 权限
// baseURL 基础URL
在vue中使用全局配置 this.$axios