- 类似于ajax,用来发送请求,异步获取数据
- 安装:npm i -S axios
导入 vue
1 // 导入 axios
import axios from 'axios'
2 Vue.prototype.$http = axios
this.$http 方式来使用 axios
全局公共域名配置
axios.defaults.baseURL = 'https://api.example.com'
HTTP请求的拦截器
axios.interceptors.request
axios.interceptors.response
注意:发送post请求的时候,参数需要额外的处理
import Vue from 'vue'
import axios from 'axios'
// 将 axios 添加到 Vue.prototype 中
Vue.prototype.$http = axios
---
// 在组件中使用:
methods: {
getNewsInfo() {
this.$http.get(`http://182.254.146.100:8899/api/getnew/${this.$route.params.id}`)
.then(res => {
const data = res.data;
if (data.status === 0) {
this.info = data.message[0];
}
})
.catch(function (error) {
console.log(error);
});
}
},
---
// API使用方式:
axios.get(url[, config])
axios.post(url[, data[, config]])
axios(url[, config])
axios(config)
Get 请求
this.$http.get(`http://182.254.146.100:8899/api/getnew/${this.$route.params.id}`)
.then(res => {
const data = res.data;
if (data.status === 0) {
this.info = data.message[0];
}
})
.catch(function (error) {
console.log(error);
});
Post请求
- 不同环境中处理 POST请求
- 默认情况下,axios 会将JS对象序列化为JSON对象。为了使用 application/x-www-form-urlencoded 格式发送请求,我们可以这样:
let url = "api/postcomment/${this.commentId}";
this.$http.post(url, "content=" + this.content).then(res => {
console.log(res);
const data = res.data;
if (data.status === 1) {
this.list.unshift({
add_time: new Date(),
content: this.content,
user_name: "匿名用户"
});
Toast({
message: '发表成功',
duration: 500
})
//清空文本内容
this.content=''
}
})
.catch(err=>console.log(err))
axios API
可以通过传递相关配置来进行请求axios
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
全局配置
```js // 设置请求公共路径: axios.defaults.baseURL = 'https://api.example.com'
### 拦截器
```js
// 请求拦截器
axios.interceptors.request.use(function (config) {
// Do something with response data
return config;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
// 响应拦截器
axios.interceptors.response.use(function (response) {
// 所有请求完成后都要执行的操作
return response;
}, function (error) {
// 错误处理
return Promise.reject(error);
});
官方链接:https://github.com/axios/axios