如何通过HTTP客户端(如axios或fetch)实现前后端交互

HTTP请求参数三种类型:查询参数(Query)、请求体参数(Body)、路径参数(Path)

1.查询参数(Query)

  • 查询参数位于URL的末尾,以?开始,多个参数之间用&分隔。例如:https://example.com/api/data?key1=value1&key2=value2

2.请求体参数(Body)

  • 请求体参数存储在HTTP请求的消息体中,常见于POST、PUT、PATCH等方法。

3.路径参数(Path)

  • 路径参数直接嵌入到URL路径中,作为URL的一部分,用于标识资源的特定实例或区分不同的资源。例如:https://example.com/api/users/{userId},其中{userId}就是一个路径参数。

(一)使用Query参数实现交互

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
 const userDetails = ref(null);

    const fetchUserDetails = async () => {
      try {
        const response = await axios.get('/api/users', {
          params: { id: '123' } // 这里是查询参数
        });
        userDetails.value = response.data;
      } catch (error) {
        console.error('Error fetching user details:', error);
      }
    };

    onMounted(() => {
      fetchUserDetails();
    });
</script>

(二)使用Query参数实现交互


<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
 const newUserResponse = ref(null);

    const createUser = async () => {
      try {
        const userData = {
          name: 'John Doe',
          email: 'john.doe@example.com'
        };
        const response = await axios.post('/api/users', userData); // 这里是请求体
        newUserResponse.value = response.data;
      } catch (error) {
        console.error('Error creating user:', error);
      }
    };

    onMounted(() => {
      createUser();
    });
</script>

(三)使用path参数实现交互

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
 const userDetails = ref(null);

    const fetchUserDetails = async () => {
      try {
        const response = await axios.get(`/api/users/${urlsId}`); // 路径参数
        userDetails.value = response.data;
      } catch (error) {
        console.error('Error fetching user details:', error);
      }
    };

    onMounted(() => {
      fetchUserDetails();
    });
</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值