首页 > 其他分享 >vue之axios

vue之axios

时间:2022-10-19 11:05:28浏览次数:71  
标签:function axios console log vue error response

什么是 axios?

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

特性

1 从浏览器中创建 XMLHttpRequests
2 从 node.js 创建 http 请求
3 支持 Promise API
4 拦截请求和响应
5 转换请求数据和响应数据
6 取消请求
7 自动转换 JSON 数据
8

安装

npm install axios

使用

GET请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

POST请求

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

并发

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 API

// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 获取远端图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
// 发送 GET 请求(默认的方法)
axios('/user/12345');

创建实例

const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
import axios from 'axios'
import { getToken } from '@/utils/auth'

// axios.defaults.headers.common['Authorization'] = getToken(); //设置headers
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


// 创建axios实例
const service = axios.create({
baseURL: 'http://127.0.0.1:8000', // api的base_url
timeout: 15000, // 请求超时时间
// headers: { // 设置headers
// // 'X-Custom-Header': 'foobar',
// 'Authorization': getToken(),
// 'Content-Type': 'application/x-www-from-urlencoded'
// }
})

// request拦截器
service.interceptors.request.use(config => {
if (store.getters.token) {

config.headers= {
'Authorization': getToken(),
'Content-Type': 'application/x-www-from-urlencoded' // 跨域设置headers
}
// config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
// config.headers['Authorization'] = AUTH_TOKEN, // 让每个请求携带自定义token 请根据实际情况自行修改
// config.headers['Content-Type'] = 'application/x-www-from-urlencoded'
}
return config
}, error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
response => {
/**
* code为非200是抛错 可结合自己业务进行修改
*/
const res = response.data

if (res.code !== 200) {
Message({
message: res.message,
type: 'error',
duration: 3 * 1000
})

// 401:未登录;
if (res.code === 401) {
MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload()// 为了重新实例化vue-router对象 避免bug
})
})
}
return Promise.reject('error')
} else {
console.log(response.data,"return")
return response.data
}
},
error => {
console.log('err' + error)// for debug
Message({
message: error.message,
type: 'error',
duration: 3 * 1000
})
return Promise.reject(error)
// return response.data
}
)

export default

全局的 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';

自定义实例默认值

// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

配置会以一个优先顺序进行合并。这个顺序是:在 ​​lib/defaults.js​​​ 找到的库的默认值,然后是实例的 ​​defaults​​​ 属性,最后是请求的 ​​config​​ 参数。后者将优先于前者。这里是一个例子:

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 `0`
var instance = axios.create();

// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
instance.defaults.timeout = 2500;

// 为已知需要花费很长时间的请求覆写超时设置
instance.get('/longRequest', {
timeout: 5000
});

拦截器

在请求或响应被 ​​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);
});

如果你想在稍后移除拦截器,可以这样:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
可以为自定义 axios 实例添加拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

错误处理

axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});

也可以使用 ​​validateStatus​​ 配置选项定义一个自定义 HTTP 状态码的错误范围。

axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})

使用 application/x-www-form-urlencoded format

默认情况下,axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。

在浏览器中,您可以使用URLSearchParams API,如下所示:

onst params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

使用qs库编码数据:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123

本文来自​​axios中文文档|axios中文网​



标签:function,axios,console,log,vue,error,response
From: https://blog.51cto.com/aaronthon/5769005

相关文章

  • 【Vue】图片拉近、全屏背景实战经验总结
    1图片拉近缘起是看到了下面的图片,我发现当鼠标悬浮的时候,发现他是可以拉近的,也就是图片的宽高不变,但是图片被放大了起初我以为是有一个这样的方法,可以实现这个操作,但是查找......
  • 从0搭建vue3组件库:Shake抖动组件
    先看下效果其实就是个抖动效果组件,实现起来也非常简单。之所以做这样一个组件是为了后面写Form表单的时候会用到它做一个规则校验,比如下面一个简单的登录页面,当点击登录......
  • vue组件通信6种方式总结(常问知识点)
    前言在Vue组件库开发过程中,Vue组件之间的通信一直是一个重要的话题,虽然官方推出的Vuex状态管理方案可以很好的解决组件之间的通信问题,但是在组件库内部使用Vuex往往会......
  • VUE 代码压缩优化
    1、设置productionSourceMap为false如果不需要生产环境的sourcemap,可以将其设置为false以加速生产环境构建。设置为false打包时候不会出现.map文件module.exports......
  • 用Typescript 的方式封装Vue3的表单绑定,支持防抖等功能。
    Vue3的父子组件传值、绑定表单数据、UI库的二次封装、防抖等,想来大家都很熟悉了,本篇介绍一种使用Typescript的方式进行统一的封装的方法。基础使用方法Vue3对于表单的绑......
  • 快速卸载Vue脚手架(vue-cli
    一、卸载vue-cli执行命令:npmuninstallvue-cli-g或者npmunivue-cli-g检查vue-cli卸载成功没执行命令:vue-V出现‘vue’不是内部或外部命令,也不是可运行的程序,代......
  • vue路由传参,query和params的区别
    路由传参是使用vue最常用的方法,而其中query和params都能实现传参效果,不过这两者还是有区别的首先路由配置{path:'/admin',//组件路径name:'admin',//组件别名com......
  • 解决Vue打印el-table不完全的pdf问题
    智能中医项目中的打印报告要新增一项异常检测表格的显示,纸张定为A4纸张竖向打印,在使用el-table后发现,虽然页面中显示无误,但不管怎么样设置table的宽度,打印的pdf中最后一列......
  • vue中页面调用多次组件,会出现组件之间相互影响
    这个大部分发生在echarts和地图中,我们为了节省性能把echarts和map对象没有绑定在vue对象上导致,一个页面多次调用时会出现问题,解决办法:如果确定一个页面调用多次了,就把echa......
  • RuoYi-Vue切换达梦数据库(一)
    一、达梦数据库安装这里使用的达梦8开发版 ,安装过程没什么且包内有说明文档。要注意的点是创建数据库实例时,记得取消勾选字符串比较大小写敏感。二、达梦数据库用户设......