乐闻世界logo
搜索文章和话题

How to post query parameters with Axios?

7 个月前提问
3 个月前修改
浏览次数169

5个答案

1
2
3
4
5

在使用 Axios 进行 POST 请求时,通常情况下,查询参数(query parameters)会附加在 URL 中,而请求体(request body)通常包含 POST 数据。如果你需要在 POST 请求中设置查询参数,你可以直接在 URL 中加入它们,或者使用 params 配置选项来指定这些参数。

下面是一个如何在 Axios POST 请求中设置查询参数的具体例子:

javascript
const axios = require('axios'); // 设置 POST 请求的数据 const postData = { key1: 'value1', key2: 'value2' }; // 设置查询参数 const queryParams = { param1: 'value1', param2: 'value2' }; // 发起 POST 请求 axios.post('https://example.com/api/resource', postData, { params: queryParams }) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); });

在这个例子中,postData 是要发送到服务器的数据,而 queryParams 是我们想要附加在 URL 上的查询参数。通过 params 配置,Axios 会自动将查询参数拼接到请求的 URL 上。

生成的请求 URL 将类似于这样:

shell
https://example.com/api/resource?param1=value1&param2=value2

同时,postData 中的内容会作为 POST 请求体发送。这种方式使得你可以同时在一个 POST 请求中发送请求体数据和查询参数。

2024年6月29日 12:07 回复

截至 2021 年,安装了 null 我必须添加 {} 才能使其正常工作!

shell
axios.post( url, {}, { params: { key, checksum } } ) .then(response => { return success(response); }) .catch(error => { return fail(error); });
2024年6月29日 12:07 回复

就我而言,API 响应了 CORS 错误。相反,我将查询参数格式化为查询字符串。它成功地发布了数据,并且还避免了 CORS 问题。

shell
var data = {}; const params = new URLSearchParams({ contact: this.ContactPerson, phoneNumber: this.PhoneNumber, email: this.Email }).toString(); const url = "https://test.com/api/UpdateProfile?" + params; axios .post(url, data, { headers: { aaid: this.ID, token: this.Token } }) .then(res => { this.Info = JSON.parse(res.data); }) .catch(err => { console.log(err); });
2024年6月29日 12:07 回复

您可以在 axios 请求中同时使用 params 和 body

shell
sendAllData (data) { return axios .post(API_URL + "receiveData", JSON.stringify(data), { headers: { "Content-Type": "application/json; charset=UTF-8" }, params: { mail: xyx@example.col }, //Add mail as a param }) .then((response) => console.log("repsonse", response.status)); }
2024年6月29日 12:07 回复

你的答案