在 Axios 中,发送不同参数的请求可以通过多种方式实现。
将介绍几种不同的请求参数写法,包括在 URL 中嵌入参数、使用查询参数、以及使用请求体。
1.在 URL 中嵌入参数
使用模板字符串嵌入:
const id = res.data.data.record[0].id;
return axiosInstance({
url: `/user/${id}`, // 使用模板字符串嵌入 id
method: 'get',
});
2.使用查询参数
在这个例子中,最终的请求 URL 会是 /user?id=1
,其中 id
是作为查询参数传递的。
const id = res.data.data.record[0].id;
return axiosInstance({
url: '/user', // 不在 URL 中嵌入 id
method: 'get',
params: { id } // 使用 params 传递查询参数
});
3.使用请求体(适用于 post , put 等请求)
若要发送一个 post 请求,并且需要在请求体中传递参数,可以这样写:
const userData = {
id: res.data.data.record[0].id,
name: 'Alice'
};
return axiosInstance({
url: '/user',
method: 'post', // 使用 POST 请求
data: userData // 将数据放入请求体
});
在这个例子中,请求将会发送一个包含 id
和 name
的 JSON 对象到服务器。
4. 使用 URL 参数和查询参数结合
const id = res.data.data.record[0].id;
return axiosInstance({
url: `/user/${id}`, // URL 中嵌入 id
method: 'get',
params: { detail: true } // 额外的查询参数
});
在这个例子中,请求的最终 URL 将会是 /user/1?detail=true
,其中 detail
是作为查询参数传递的。
5.使用 axios 的 params 选项
可以直接在 Axios 的配置中使用 params
选项,这样可以更方便地构建查询参数
const id = res.data.data.record[0].id;
return axiosInstance.get('/user', {
params: { id } // 直接使用 get 方法并传递参数
});