axios并发
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
// axios.all类似于Promise.all
Promise.all([getUserAccount(), getUserPermissions()])
.then(res=>{
console.log(res); // Promise.all返回的res是一个数组
})
复制代码
axios配置vue-cli跨域请求
// server.js 模拟后端接口
let http = require('http')
http.createServer((req,res)=>{
// res.setHeader('Access-Control-Allow-Origin','*')
/* 下面是后端返回的结果 */
res.end('tsuccess...')
/* 3000是端口 */
}).listen(3000,function(){
console.log('server start...')
})
复制代码
// vue.config.js 配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000/',
}
}
}
})
复制代码
// App.vue
axios.get('/api').then(res=>{ cnsole.log(res) })
复制代码
局部配置axios--创建axios实例
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
复制代码
全局配置axios
在父组件全局配置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';
复制代码
axios的请求拦截器与返回拦截器
在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});