Axios基本使用
介绍
Axios 是一个基于promise网络请求库,作用于node.js和浏览器中
特性
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
安装
项目中
npm install axiosyarn add axios
学习阶段
<script src=\"https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js\"></script><script src=\"https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js\"></script>
基本使用
axios({ //方法 method: \"\", //url url: \"\", //设置请求体 //data: {}}).then(response => { console.log(response); //...});
API
axios.request(config)
axios.request({ //方法 method: \"\", //url url: \"\",}).then(response => { console.log(response); //...});
axios.post(url[, data[, config]])
axios.post(\"http://....\", { \"body\":\"喜大普奔\", \"postId\":2}).then(response => { console.log(response); //...});
其他
axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])
axios返回结果
config:为axios配置项,
data:服务器返回的数据,axios默认做json转换。
headers:http响应头
request: 原生ajax对象
status:状态码
statusText:状态描述
axios 配置对象
这些是用于发出请求的可用配置选项。
{ url: \'/user\', method: \'get\', // default baseURL: \'https://some-domain.com/api/\', //对请求数据做预先处理 transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], //对响应数据进行预处理 transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // 请求头信息配置 headers: {\'X-Requested-With\': \'XMLHttpRequest\'}, //发送请求时url后边的参数?id=12345&name=张三 params: { ID: 12345, name:\"张三\" }, // `paramsSerializer` is an optional config in charge of serializing `params` 一般用的不多 paramsSerializer: { encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashion serialize?: (params: Record, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized. indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes) }, //第一种data形式,对象形式 data: { firstName: \'Fred\' }, //第一种data形式,字符串形式 data:\'Country=Brasil&City=Belo Horizonte\', //请求时间 timeout: 1000, //跨域请求是否把cookie携带过去,false不携带 withCredentials: false, responseType: \'json\', // default responseEncoding: \'utf8\', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: \'XSRF-TOKEN\', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: \'X-XSRF-TOKEN\', // default ... //代理,一般用在nodejs里面 proxy: { protocol: \'https\', host: \'127.0.0.1\', // hostname: \'127.0.0.1\' // Takes precedence over \'host\' if both are defined port: 9000, auth: { username: \'mikeymike\', password: \'rapunz3l\' } }, ...}
设置默认配置
axios.defaults.method = \"get\";axios.defaults.baseURL = \"https://api.apiopen.top\";axios.defaults.params = { page: 0, size: 5}axios.defaults.timeout = 3000axios({ //url url: \"/api/getHaoKanVideo\"}).then(response => { console.log(response);});
创建实例对象发送请求
const a1 = axios.create({ baseURL: \'https://some-domain.com/api/\', timeout: 1000, headers: {\'X-Custom-Header\': \'foobar\'}});const a2 = axios.create({ baseURL: \'https://api.apiopen.top\', timeout: 1000, headers: {\'X-Custom-Header\': \'foobar\'}});//发送请求a1({ url:\"xxxx\", method:\"get\"}).then(response => { console.log(response);})
当需要请求不同域名发送不同请求时可以创建实例对象去发送请求。
下面列出了可用的实例方法。指定的配置将与实例配置合并。
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#getUri([config])
拦截器
拦截器其实是一些函数,可以在请求和响应之前处理数据、权限判断等。
//请求拦截器axios.interceptors.request.use(function (config) { //可以对config进行设置 throw (\"error\") //return config;}, function (error) { return Promise.reject(error);});//响应拦截器axios.interceptors.response.use(function (response) { //可以对response进行处理 return response;}, function (error) { return Promise.reject(error);});axios({ method:\"get\", url: \"http://localhost:3300/api/getHaoKanVideo\"}).then(response => { console.log(response);});
如果请求拦截器抛出异常,那么响应拦截器执行use中第二个参数回调方法。
请求拦截器执行顺序与响应拦截器不同:
axios.interceptors.request.use(function (config) { console.log(\"请求拦截器-1\") return config;}, function (error) { return Promise.reject(error);});axios.interceptors.request.use(function (config) { console.log(\"请求拦截器-2\") return config;}, function (error) { return Promise.reject(error);});//响应拦截器axios.interceptors.response.use(function (response) { console.log(\"请求拦截器-1\") return response;}, function (error) { return Promise.reject(error);});axios.interceptors.response.use(function (response) { console.log(\"请求拦截器-2\")}, function (error) { return Promise.reject(error);});axios.defaults.method = \"get\";axios.defaults.baseURL = \"https://api.apiopen.top\";axios.defaults.params = { page: 0, size: 5}axios({ //url url: \"/api/getHaoKanVideo\"}).then(response => { console.log(\"执行结果-3\") console.log(response);});
执行的结果为:
请求拦截器后加入的会先执行。