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>