我的 axios POST 方法无法正常工作。虽然调用语法似乎是正确的,但我想在我的具体情况下存在一些根深蒂固的问题。我正在尝试使用 grant_type=client_credentials 获取访问 token ,使用对 fiware IDM 服务器的 POST 请求。调用结果为 400: bad request
。
curl 命令效果很好。当我使用简单的http请求时,似乎存在CORS违规,因此我改用node.js。我尝试通过在单独的正文中发送数据来尝试 axios,它也不起作用,然后有人建议使用 axios.post 在调用中发送数据,它也以同样的问题结束。注意:我尝试过 grant_type=password
,但是,也遇到了同样的命运。
axios.post('https://account.lab.fiware.org/oauth2/token',{
'grant_type':'client_credentials'},{
headers:
{
'Content-Type':'application/x-www-form-urlencoded',
'Authorization': 'Basic xxxx'
}
}).then((response) => {
console.log(response);
}).catch((error) =>{
console.log(error.response.data.error);
})
我希望获得访问 token ,但是,我收到错误 400,如下所示:
{ message: 'grant_type missing in request body: {}',
code: 400,
title: 'Bad Request' }
最佳答案
问题是因为 https://account.lab.fiware.org/oauth2/token
的主机希望正文数据为 x-www-form-urlencoded
,但 axios
正在为您将正文转换为 json
。这是 axios
的默认行为。
更改您的 axios 代码以发送 x-www-form-urlencoded
正文数据,例如:
// use querystring node module
var querystring = require('querystring');
axios.post('https://account.lab.fiware.org/oauth2/token',{
// note the use of querystring
querystring.stringify({'grant_type':'client_credentials'}),{
headers: {
'Content-Type':'application/x-www-form-urlencoded',
'Authorization': 'Basic xxxx'
}
}).then(...
关于node.js - axios.post 导致错误请求 - grant_type :'client_credentials',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557557/