2024年最新Vue进阶(三):Axios 应用详解_vue axios,携程 前端面试

基础面试题

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

主要内容包括:HTML,CSS,JavaScript,浏览器,性能优化等等

return data;
}],

// headers are custom headers to be sent
headers: {‘X-Requested-With’: ‘XMLHttpRequest’},

// params are the URL parameters to be sent with the request
params: {
ID: 12345
},

// paramsSerializer is an optional function in charge of serializing params
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: ‘brackets’})
},

// data is the data to be sent as the request body
// Only applicable for request methods ‘PUT’, ‘POST’, and ‘PATCH’
// When no transformRequest is set, must be a string, an ArrayBuffer or a hash
data: {
firstName: ‘Fred’
},

// timeout specifies the number of milliseconds before the request times out.
// If the request takes longer than timeout, the request will be aborted.
timeout: 1000,

// withCredentials indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default

// adapter allows custom handling of requests which makes testing easier.
// Call resolve or reject and supply a valid response (see response docs).
adapter: function (resolve, reject, config) {
/* … */
},

// auth indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an Authorization header, overwriting any existing
// Authorization custom headers you have set using headers.
auth: {
username: ‘janedoe’,
password: ‘s00pers3cret’
}

// responseType indicates the type of data that the server will respond with
// options are ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’
responseType: ‘json’, // 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

// progress allows handling of progress events for ‘POST’ and ‘PUT uploads’
// as well as ‘GET’ downloads
progress: function(progressEvent) {
// Do whatever you want with the native progress event
}
}


#### 4.2 响应的数据结构


响应的数据包括下面的信息:



{
// 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 headers that the server responded with
headers: {},

// config is the config that was provided to axios for the request
config: {}
}


当使用 `then` 或者 `catch` 时, 会收到下面的响应:



axios.get(‘/user/12345’)
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});


### 五、示例


#### 5.1 发送 GET 请求



// Make a request for a user with a given ID
axios.get(‘/user?ID=12345’)
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
// Optionally the request above could also be done as
axios.get(‘/user’, {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});


#### 5.2 发送 POST 请求



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


#### 5.3 发送多个并发请求


处理并发请求方法如下:



axios.all(iterable)
axios.spread(callback)



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) {
// Both requests are now complete
}));


可以通过给 `axios`传递对应的参数来定制请求:



axios(config)
// Send a POST request
axios({
method: ‘post’,
url: ‘/user/12345’,
data: {
firstName: ‘Fred’,
lastName: ‘Flintstone’
}
});
axios(url[, config])
// Sned a GET request (default method)
axios(‘/user/12345’);


### 六、请求方法别名


为方便起见,`axios`为所有支持的请求方法都提供了别名。



axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])



> 
> 注意: 当使用别名方法时, `url`、 `method` 和 `data` 属性不需要在 `config` 参数里面指定。
> 
> 
> 


### 七、默认配置


可以为每一个请求指定默认配置。


#### 7.1 全局 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’;


#### 7.2 自定义实例默认配置



// Set config defaults when creating the instance
var instance = axios.create({
baseURL: ‘https://api.example.com’
});
// Alter defaults after instance has been created
instance.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;


#### 7.3 配置的优先顺序



> 
> Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here’s an example.
> 
> 
> 



// Create an instance using the config defaults provided by the library
// At this point the timeout config value is 0 as is the default for the library
var instance = axios.create();

// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it’s known to take a long time
instance.get(‘/longRequest’, {
timeout: 5000
});


### 八、拦截器


#### 8.1 添加拦截器


可以在处理 `then` 或 `catch` 之前拦截请求和响应。



// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});


#### 8.2 移除一个拦截器



var myInterceptor = axios.interceptors.request.use(function () {/*…*/});
axios.interceptors.request.eject(myInterceptor);


也可以给自定义的 `axios` 实例添加拦截器:





### 最后

除了简历做到位,面试题也必不可少,整理了些题目,前面有117道汇总的面试到的题目,后面包括了HTML、CSS、JS、ES6、vue、微信小程序、项目类问题、笔试编程类题等专题。

* **[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0)**

  ![](https://img-blog.csdnimg.cn/img_convert/64ce8432d0f753e43f93972ad19fcd72.png)


![](https://img-blog.csdnimg.cn/img_convert/d508b1ae6a5e7d5e7d5daf668e9eccea.png)



题目,前面有117道汇总的面试到的题目,后面包括了HTML、CSS、JS、ES6、vue、微信小程序、项目类问题、笔试编程类题等专题。

* **[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0)**

  ![](https://img-blog.csdnimg.cn/img_convert/64ce8432d0f753e43f93972ad19fcd72.png)


![](https://img-blog.csdnimg.cn/img_convert/d508b1ae6a5e7d5e7d5daf668e9eccea.png)



  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值