导航
引入:
语法:
// GET
this.$axios.get("/news/list?type=gn")
.then(res => {
console.log(res.data.result);
})
.catch(err => {
console.log(err);
});
// or
this.$axios.get("/news/list", {
params: {
type: 'gn'
}
})...
// POST
this.$axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
应用场景:必须保证两次请求都成功,e.g. 分头获取省、市的数据
执行特点:只要有一个请求失败就算失败,否则成功
语法:
this.$axios.all([
this.$axios.get("/news/list?type=gn"),
this.$axios.get("/news/list?type=js"),
])
.then(this.$axios.spread((res1, res2) => {
console.log(res1.data);
console.log(res2.data);
}))
.catch(err => {
console.log(err);
});
作用:过滤,在每一次请求与响应中、添油加醋
语法:
// main.js
Axios.interceptors.request.use(function(config) {
console.log(config);
config.header = { xxx }
return config;
})
在请求发起前open,在响应回来后close
// mint-ui库
import MintUI from 'mint-ui';
import 'mint-ui/lib/style.css';
Vue.use(MintUI);
// 拦截请求
Axios.interceptors.request.use(function(config) { // 请求配置
MintUI.Indicator.open("加载中");
return config;
});
// 拦截响应
Axios.interceptors.response.use(function(response) { // 响应结果
let {
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
} = response
MintUI.Indicator.close();
return response;
});
跨域+post请求的时候,
注意:
发送请求后的 Form Data 的正确格式应该是:key=value&key-value 的形式,而不是json的形式