-
1.2 Axios中Get请求
-
本文以vue为例,介绍axios的基本用法。
第一步.先用npm安装axios
npm install axios --save
第二步:引入axios
import axios from "axios";
Get请求用法:
const axios = require("axios"); // 向给定 ID 的用户发起请求 axios.get("/user?ID=12345") .then(function (response) { //处理成功情况 console.log(response); }) .catch(function (error) { //处理错误情况 console.log(error); }) .then(function () { //总是会执行 }); // 上述请求也可以按以下方式完成 axios.get("/user", { params: { ID: 12345, }, }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { //总是会执行 }); // 支持 async/await 用法 async function getUser() { try { const response = await axios.get("/user?ID=12345"); console.log(response); } catch (error) { console.error(error); } }
一个简单的完整Get请求实例:
<script lang="ts"> import axios from "axios"; export default { data() { return { userInfo: { id:123, name: "张三", sex: "boy" } }; }, methods: { GetUserInfo(id: any) { // 向给定 ID 的用户发起请求 axios.get("/user?ID=12345") .then(function (response) { //处理成功情况 console.log(response); }) .catch(function (error) { //处理错误情况 console.log(error); }) .then(function () { //总是会执行 }); }, } }; </script>
- 留下你的读书笔记
- 你还没登录,点击这里
-
用户笔记留言