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

标签 node.js post oauth-2.0 axios fiware

我的 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/

相关文章:

node.js - child_process中的spawnSync函数不返回任何内容

php - $_POST 没有值(value)

java - 从 servlet 调用 servlet

javascript - session 不是持久的 [PASSPORT]

azure - 我如何知道哪些用户正在访问 Azure AD OAuth 2.0 中托管的 API,以便他们只能访问自己的私有(private)数据?

node.js - 如何通过GitHub API访问私有(private)仓库?

javascript - 如何在 Node 中使用 `monet-pimp`?

c# - 发布方法并使用某些值重定向而不使用 Form C#

rest - Jersey 的 RestFul API 的 2 足 OAuth 安全性

javascript - Discord.js/javascript 问题出现错误。引用错误 : command not defined