我显然忽略了这里的一些东西:
我正在尝试从Here将cURL请求转换为axios。
curl -d "grant_type=client_credentials\
&client_id={YOUR APPLICATION'S CLIENT_ID} \
&client_secret={YOUR APPLICATION'S CLIENT_SECRET}" \
https://oauth.nzpost.co.nz/as/token.oauth2这工作得很好(当我输入我的凭证时)
我尝试了以下代码:
import axios from "axios";
async function testApi() {
try {
const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2", {
client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
grant_type: "client_credentials"
});
} catch (error) {
console.log(error);
}
}
testApi();此操作失败。错误400。grant_type是必需的。我尝试将其作为参数,封装在data: json块中。我搞不懂这事!
发布于 2019-03-27 13:52:41
我修复了它,我需要将值放入参数中
import axios from "axios";
async function testApi() {
try {
const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2",
params: {
client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
grant_type: "client_credentials"
});
} catch (error) {
console.log(error);
}
}
testApi();发布于 2020-11-10 15:27:19
提醒一下,curl -d只是curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d的缩写。它是POST请求,即使没有指定-X POST!
因此,您需要将axios请求配置为POST请求,同时还要确保您的数据是URL编码的,并将Content-Type头设置为application/x-www-form-urlencoded。例如..。
const response = await axios({
url: 'example.com',
method: 'post',
headers: {
'Content-Type': 'x-www-form-urlencoded'
},
// For Basic Authorization (curl -u), set via auth:
auth: {
username: 'myClientId',
password: 'myClientSecret'
},
// This will urlencode the data correctly:
data: new URLSearchParams({
grant_type: 'client_credentials'
})
};https://stackoverflow.com/questions/55370000
复制相似问题