gpt4 book ai didi

javascript - axios 使用数据服务器参数

转载 作者:行者123 更新时间:2023-12-02 21:45:49 25 4
gpt4 key购买 nike

我正在尝试 axios 联系远程服务器如果我使用以下格式,我的服务器似乎永远不会解析数据参数

axios({
url: API_URL + 'oauth/token',
method:'post',
data: {
grant_type: 'password',
username: user.username,
password: user.password,
scope: 'webclient'
},
auth: {
username: 'foo',
password: 'foobar'
},
responseType: 'json'
})

但是如果我使用粗俗的格式

axios({
url: API_URL + 'oauth/token',
method: 'post',
data:'grant_type=password&username='+user.username+'&password='+user.password+'&scope=webclient',
auth: {
username: 'foo',
password: 'foobar'
},
responseType: 'json'
})

一切都按预期工作,所以有人可以告诉我两种不同形式的数据参数之间有什么区别吗?

最佳答案

如果您将一个对象传递给 data,那么 Axios 会将其编码为 JSON,而不是 URL 表单编码数据(这是您的手动编码使用的内容,因此大概也是您的服务器所期望的)。

The documentation有几个以编程方式编码数据的示例:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

确保您还将 'application/x-www-form-urlencoded' 设置为 Content-Type 请求 header 。

关于javascript - axios 使用数据服务器参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com