axios.post导致请求错误-grant_type:'client_credentials'

时间:2019-04-07 09:39:12

标签: node.js post oauth-2.0 axios fiware

我的axios POST方法无法正常工作。尽管调用语法似乎是正确的,但我想在我的具体情况下还是存在一些根深蒂固的问题。我试图使用Grant_type = client_credentials来获取访问令牌,并使用对软件IDM服务器的POST请求。通话结果为400: bad request

curl命令效果很好。当我使用简单的http请求时,似乎出现了CORS违规,因此我切换到使用节点。我尝试通过在单独的正文中发送数据来尝试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);
    })

我希望获得访问令牌,但是,出现以下错误400:

{ message: 'grant_type missing in request body: {}',
code: 400,
title: 'Bad Request' }

1 个答案:

答案 0 :(得分:0)

问题是因为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(...
相关问题