在 Vue 中用 Axios 异步请求API 您所在的位置:网站首页 axios调用 在 Vue 中用 Axios 异步请求API

在 Vue 中用 Axios 异步请求API

#在 Vue 中用 Axios 异步请求API| 来源: 网络整理| 查看: 265

Axios 是 Javascript 中最受欢迎的 HTTP 库之一,我们可以用它在 Vue 程序中调用API。

在本文中我们用 Vue 3 和 Axios 写一个侃爷语录小应用,侃爷是国内粉丝对美国当红饶舌歌手 Kanye West 的昵称。可以用这个小程序学习英语,同时也能从侃爷的话中得到一些启发,而且还可以学习用 Vue 异步请求API,一举多得,何乐而不为呢?

设置基本 HTTP 请求

首先在终端中执行下面的命令把 Axios 安装到项目中:

install axiosnpm install axios 

然后,在 Vue 组件中像这样导入axios。

//App.vie - importing axios  import axios from 'axios'  export default {   setup () {      } }  

接下来用 axios.get 通过 Kanye REST API 的 URL 获取随机语录。之后可以用 Promise.then 等待请求返回响应。

//App.vue - sending our HTTP request  import axios from 'axios'  export default {   setup () {      axios.get('https://api.kanye.rest/').then(response => {         // handle response      })   } }  

现在可以从 API 中获取响应了,先看一下它的含义。把它保存成名为 quote 的引用。

//App.vue - storing the response  import axios from 'axios' import { ref } from 'vue'  export default {   setup () {      axios.get('https://api.kanye.rest/').then(response => {         // handle response         quote.value = response      })      return {       quote      }   } }  

最后将其输出到模板中并以斜体显示,并用引号引起来,另外还需要给这条语录加上引用来源。

//App.vue - template code         "{{ quote }}"     - Kanye West     

检查一下浏览器中的内容。

我们可以看到随机返回的侃爷语录,还有一些额外的信息,例如请求的响应码等。

对于我们这个小应用,只对这个 data.quote 值感兴趣,所以要在脚本中指定要访问 response 上的哪个属性。

//App.vue - getting only our quote axios.get('https://api.kanye.rest/').then(response => {         // handle response         quote.value = response.data.quote }) 

通过上面的代码可以得到想要的内容:

Axios 配合 async/await

可以在 Vue 程序中把 Axios 和 async /await 模式结合起来使用。

在设置过程中,首先注释掉当前的 GET 代码,然后创建一个名为 loadQuote 的异步方法。在内部,可以使用相同的 axios.get 方法,但是我们想用 async 等待它完成,然后把结果保存在一个名为 response 的常量中。

然后设置 quote 的值。

//App.vue - async Axios const loadQuote = async () => {       const response = await KanyeAPI.getQuote()       quote.value = response.data.quote } 

它和前面的代码工作原理完全一样,但这次用了异步模式。

Axios 的错误处理

在 async-await 模式中,可以通过 try 和 catch 来为 API 调用添加错误处理:

//Error handling with async/await try {         const response = await KanyeAPI.getQuote()         quote.value = response.data.quote } catch (err) {         console.log(err) } 

如果使用原始的 promises 语法,可以在 API 调用之后添加 .catch 捕获来自请求的任何错误。

//Error handling with Promises axios.get('https://api.kanye.rest/')       .then(response => {         // handle response         quote.value = response.data.quote       }).catch(err => {       console.log(err) })  发送POST请求

下面看一下怎样发送 POST 请求。在这里我们使用 JSONPlaceholder Mock API 调用。

他们的文档中提供了一个测试 POST 请求的 /posts 接口。

接下来我们需要创建一个按钮,当点击按钮时将会触发我们的API调用。在模板中创建一个名为 “Create Post” 的按钮,单击时调用名为 createPost 方法。

   "{{ quote }}"   - Kanye West        Create Post     template> 

下面在代码中创建 createPost 方法,然后从 setup 返回。

这个方法,类似于前面的 GET 请求,只需要调用 axios.post 并传入URL(即https://jsonplaceholder.typicode.com/posts )就可以复制粘贴文档中的数据了。

//App.vue const createPost = () => {       axios.post('https://jsonplaceholder.typicode.com/posts', JSON.stringify({           title: 'foo',           body: 'bar',           userId: 1,       })).then(response => {         console.log(response)       }) } 

单击按钮试一下,可以看到控制台输出了大量信息,告诉我们 POST 请求已成功完成。

用 Axios 编写可复用的 API 调用

在项目中通过创建一个 src/services 目录,用它来组织所有 api 调用。

目录中包含 2 种类型的文件:

API.js :用来创建一个带有定义的 baseURL 的 Axios 实例,这个实例会用于所有的路由 *{specific functionality}*API.js :更具体的文件,可用于将 api 调用组织成可重用的模块

这样做的好处是可以方便的在开发和生产服务器之间进行切换,只需修改一小段代码就行了。

创建 services/API.js 文件,并将 Axios baseURL 设置为默认为 Kanye REST API。

API.jsimport axios from 'axios'  export default(url='https://api.kanye.rest') => {     return axios.create({         baseURL: url,     }) } 

接下来创建一个 KanyeAPI.js 文件并从 ./API 中导入 API。在这里我们要导出不同的 API 调用。

调用 API() 会给得到一个 Axios 实例,可以在其中调用 .get 或 .post。

//KanyeAPI.js import API from './API'  export default {     getQuote() {         return API().get('/')     }, } 

然后在 App.vue 内部,让我们的组件通过可复用的 API 调用来使用这个新文件,而不是自己再去创建 Axios。

//App.vue const loadQuote = async () => {       try {         const response = await KanyeAPI.getQuote() //  {       const response = await KanyeAPI.createPost(JSON.stringify({           title: 'foo',           body: 'bar',           userId: 1,       }))        console.log(response) } 

现在单击按钮时,可以看到专用的 API 能够正常工作。

把 API 调用移出这些 Vue 组件并放在它自己的文件的好处在于,可以在整个程序中的任何位置使用这些 API 调用。这样可以创建更多可重用和可伸缩的代码。

最终代码 // App.vue         "{{ quote }}"     - Kanye West            Create Post            import axios from 'axios' import { ref } from 'vue' import KanyeAPI from './services/KanyeAPI' export default {   setup () {      const quote = ref('')      const loadQuote = async () => {       try {         const response = await KanyeAPI.getQuote()         quote.value = response.data.quote       } catch (err) {         console.log(err)       }     }      loadQuote()          // axios.get('https://api.kanye.rest/')     //   .then(response => {     //     // handle response     //     quote.value = response.data.quote     //   }).catch(err => {     //   console.log(err)     // })      const createPost = () => {       const response = await KanyeAPI.createPost(JSON.stringify({           title: 'foo',           body: 'bar',           userId: 1,       }))        console.log(response)       // axios.post('https://jsonplaceholder.typicode.com/posts', JSON.stringify({       //     title: 'foo',       //     body: 'bar',       //     userId: 1,       // })).then(response => {       //   console.log(response)       // })            }          return {       createPost,       quote     }   } }    #app {   font-family: Avenir, Helvetica, Arial, sans-serif;   -webkit-font-smoothing: antialiased;   -moz-osx-font-smoothing: grayscale;   text-align: center;   color: #2c3e50;   margin-top: 60px; }   //API.js import axios from 'axios'  export default(url='https://api.kanye.rest') => {     return axios.create({         baseURL: url,     }) }  //KanyeAPI.js import API from './API' export default {     getQuote() {         return API().get('/')     },     createPost(data) {         return API('https://jsonplaceholder.typicode.com/').post('/posts', data)     } } 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有