九、网络请求

一、axios

1、基本使用

文档

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

axios是vue作者推荐使用的网络请求库,它具有以下特性:

  • 从浏览器中创建 XMLHttpRequests

  • 从 node.js 创建 http 请求

  • 支持 Promise API

  • 拦截请求和响应

  • 转换请求数据和响应数据

  • 取消请求

  • 自动转换 JSON 数据

  • 客户端支持防御 XSRF

安装

npm install axios

执行get请求

复制代码
 1 // GET请求方式
 2 axios.get('/get_data?id=10010').then(ret => console.log(ret.data))
 3 
 4 axios.get('/get_data',{
 5     params: {
 6         id: 10010,
 7         name: 'zhangsan',
 8         age: 26
 9     }
10 }).then(ret => console.log(ret.data))
复制代码

执行post请求

1 //POST请求方式
2 axios.post('/set_data', {
3       firstName: 'zhang',
4       lastName: 'san'
5 }).then(ret => { })

axios(config)方式

复制代码
 1 axios({
 2       method: 'post',
 3       url: 'set_data',
 4       timeout: 1000,
 5       headers: {'X-Custom-Header': 'foobar'},
 6       data: {
 7         firstName: 'zhang',
 8         lastName: 'san'
 9       }
10 }).then(ret => { })
复制代码

执行并发请求

复制代码
 1 function getUserAccount() {
 2   return axios.get('/user/12345');
 3 }
 4 
 5 function getUserPermissions() {
 6   return axios.get('/user/12345/permissions');
 7 }
 8 
 9 axios.all([getUserAccount(), getUserPermissions()])
10   .then(axios.spread(function (acct, perms) {
11     // 两个请求现在都执行完成
12   }));
复制代码

2、基本属性和设置

  • axios支持的请求方式

    • get

    • post

    • put:修改数据

    • delete:删除数据

  • axios响应结果的属性

    • config:配置信息

    • data:实际响应的数据

    • headers:响应头信息

    • status:响应状态码

    • statusText:响应状态信息

  • axios请求配置

1 // 设置根路径地址
2 axios.defaults.baseURL = 'https://api.example.com';
1 // 设置超时时间
2 axios.defaults.timeout = 3000;
1 // 设置请求头
2 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

3、axios实例

针对不同域名

复制代码
 1 const instace1 = axios.create({
 2     baseUrl: 'http://123.111.11.11:8000',
 3     timeout: 5000
 4 })
 5 
 6 instace1({
 7     url: '/home'
 8 }).then(res => {
 9     console.log(res)
10 })
复制代码
复制代码
 1 const instace2 = axios.create({
 2     baseUrl: 'http://123.222.22.22:9000',
 3     timeout: 10000
 4 })
 5 
 6 instace2({
 7     url: '/home'
 8 }).then(res => {
 9     console.log(res)
10 })
复制代码

4、axios封装

  • 新建src/network/request.js

复制代码
 1 import axios form 'axios'
 2 
 3 export function request(config) {
 4   // 1、创建axios实例
 5   const instance1 = axios.create({
 6     baseUrl: 'http://www.baidu.com',
 7     timeout: 5000
 8   })
 9   
10   // 2、axios拦截器
11   
12   // 3、发送真正的网络请求
13   return instance1(config)
14 }
复制代码
  • 组件中使用
复制代码
1 import { request } from '@/newwork/request.js'
2 
3 request({
4     url: '/home/mutidata'
5 }).then(res => {
6     console.log(res)
7 }).catch(err => {
8     console.log(err)
9 })
复制代码

5、拦截器

  • 请求配置:修改src/network/request.js文件

复制代码
 1 import axios form 'axios'
 2 
 3 export function request(config) {
 4   // 1、创建axios实例
 5   const instance1 = axios.create({
 6     baseUrl: 'http://www.baidu.com',
 7     timeout: 5000
 8   })
 9   
10   // 2.1、axios拦截器——请求拦截
11   instance1.interceptors.request.use(config => {
12     // 1.比如config中一些信息不符合服务器要求,需要修改
13     
14     // 2.比如每次发送网络请求时,希望在界面添加一个loading加载的图标
15     
16     // 3.某些网络请求(比如登录(需要携带token),携带一定信息)
17     
18     return config
19   }, err => {
20     console.log(err)
21   })
22   
23   // 2.2、axios拦截器——响应拦截
24   instance1.interceptors.response.use(res => {
25     // 处理响应数据
26     return res.data
27   }, err => {
28     console.log(err)
29   })
30   
31   // 3、发送真正的网络请求
32   return instance1(config)
33 }
复制代码
  • 请求封装:src/network/home.js
复制代码
 1 import { request } from './request'
 2 
 3 export function getHomeMultidata () {
 4   return request({
 5     url: '/home/mulitdata'
 6   })
 7 }
 8 
 9 export function getHomeGoods (type, page) {
10   return request({
11     url: '/home/mulitdata',
12     params: {
13       type,
14       page
15     }
16   })
17 }
复制代码
  • 组件内调用
复制代码
 1 /**
 2  * 网络请求相关方法,定义在methods中
 3  * 生命周期函数中不要写过多逻辑代码
 4  */
 5 getHomeMultidata () {
 6     getHomeMultidata().then(res => {
 7         this.banners = res.data.banner.list
 8     })
 9 },
10 getHomeGoods (type) {
11     const page = this.goods[type].page + 1
12     getHomeGoods(type, page).then(res => {
13         this.goods[type].list.push(...res.data.list)
14         this.goods[type].page += 1
15     })
16 }
复制代码

 

 

posted @   大米饭盖饭  阅读(148)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示