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

Kar*_*ali 2 post node.js oauth-2.0 fiware axios

我的 axios POST 方法无法正常工作。虽然调用语法似乎是正确的,但我想在我的具体案例中存在一些根深蒂固的问题。我正在尝试使用 grant_type=client_credentials 获取访问令牌,使用对固件 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);
    })
Run Code Online (Sandbox Code Playgroud)

我希望获得访问令牌,但是,我收到错误 400,如下所示:

{ message: 'grant_type missing in request body: {}',
code: 400,
title: 'Bad Request' }
Run Code Online (Sandbox Code Playgroud)

156*_*223 5

问题是因为主机https://account.lab.fiware.org/oauth2/token期望正文数据为x-www-form-urlencodedaxios正在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(...
Run Code Online (Sandbox Code Playgroud)