天天看點

Vue 3 和Axios 請求響應資料處理

作者:架構筆記

Axios 是一個基于 promise 的 HTTP 庫,本質是XMLHttpRequests請求即ajax請求。

Vue 3 和Axios 請求響應資料處理

Axios在浏覽器端實際上也是基于 XMLHttpRequest 來實作的,并且基于 promise 提供了一套 promise 風格的鍊式調用 API,支援請求和響應攔截、提供并發請求接口功能、輕量高效、簡單易用、用戶端支援防止CSRF等優點。也是目前使用最為廣泛的類庫之一。

一、Axios 基本使用

Axios 提供了兩種不同的形式來發送 HTTP 請求,一種是通過 axios() 方法,另一種是分别通過 axios 對象提供的與 HTTP 方法對應的方法來發起請求,如: axios.get() , axios.post() , axios.delete()。

  • axios.get(url)
  • axios.post(url,data)
  • axios.delete(url)
  • axios.update(url)
  • axios.put(url,data)

上一章的示例代碼:

axios
 .get("http://localhost:3000/posts")
 .then(function (response) {
 console.log(response.data);
 console.log("-----")
 console.log(response.status);
 console.log(response.statusText);
 console.log(response.headers);
 console.log(response.config);
 })
 .catch(function (error) {
 console.log(error);
 })           

請求響應的處理在 then 和 catch 回調中,請求正常會進入 then ,請求異常則會進 catch。

通過 axios 送出請求的響應結果中, axios 會加入一些字段,如圖所示:

響應資料簡要說明:

{
 // `data` 由伺服器提供的響應
 data: {},

 // `status` 來自伺服器響應的 HTTP 狀态碼
 status: 200,

 // `statusText` 來自伺服器響應的 HTTP 狀态資訊
 statusText: 'OK',

 // `headers` 是伺服器響應頭
 // 所有的 header 名稱都是小寫,而且可以使用方括号文法通路
 // 例如: `response.headers['content-type']`
 headers: {},

 // `config` 是 `axios` 請求的配置資訊
 config: {},

 // `request` 是生成此響應的請求
 // 在node.js中它是最後一個ClientRequest執行個體 (in redirects),
 // 在浏覽器中則是 XMLHttpRequest 執行個體
 request: {}
}           

我們在浏覽器的控制台檢視axios傳回的response結果,可以看到axios幫助我們把請求和響應結果都做了一個封裝,實際上除了data屬性外,其他的屬性都是axios為了讓我們更好地分析本次網絡請求的參數而做的封裝,一般來說我們更多是直接使用data中的資料即可。

二、頁面輸出Axios響應資料

首先,定義一個響應式變量 posts;然後,将axios 調用的響應結果指派給 posts。

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import axios from 'axios'
import { ref } from 'vue'

const posts = ref([])

const handleClick=()=>{
 axios
 .get("http://localhost:3000/posts")
 .then(function (response) {
 posts.value = response.data
 console.log(response);
 })
 .catch(function (error) {
 console.log(error);
 });
}
</script>           

在template中,使用 v-for 周遊 posts并進行輸出,示例代碼如下:

<template>
 <div>
 <a href="https://vitejs.dev" target="_blank">
 <img src="/vite.svg" class="logo" alt="Vite logo" />
 </a>
 <a href="https://vuejs.org/" target="_blank">
 <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
 </a>
 </div>
 <div>
 <button v-on:click="handleClick">擷取資料</button>
 </div>
 <div class="posts" v-if="posts.length">
 <div v-for="post in posts" :key="post.id">
 <h3>{{ post.title }}</h3>
 <p>{{ post.author }}</p>
 </div>
 </div>
 <HelloWorld msg="Vite + Vue" />
</template>           
Vue 3 和Axios 請求響應資料處理

繼續閱讀