首页 > 解决方案 > 在 Node 中使用 axios 发送 POST 数据的正确方法是什么?

问题描述

我正在尝试使用Node.js 中的axios连接到Monzo。Monzo 使用 OAuth2 发送请求,我正在努力获取访问令牌。这是文档中的请求:

http --form POST "https://api.monzo.com/oauth2/token" \
    "grant_type=authorization_code" \
    "client_id=$client_id" \
    "client_secret=$client_secret" \
    "redirect_uri=$redirect_uri" \
    "code=$authorization_code"

所以有了这个数据变量:

const data = {
  grant_type: 'authorization_code',
  client_id: oauth_12345,
  client_secret: hunter2,
  redirect_uri: https://localhost:3000/,
  code: 1234567890
};

我尝试了以下请求:

1.

var response = await axios.post("https://api.monzo.com/oauth2/token", data);

2.

const qs = require('qs'); //The qs library is used to turn objects into URL parameter strings
 var response = await axios.post("https://api.monzo.com/oauth2/token", qs.stringify(data));

3.

 const qs = require('qs');
 const config = {headers: 'Content-Type' : 'application/x-www-form-urlencoded'};
 var response = await axios.post("https://api.monzo.com/oauth2/token", qs.stringify(data), config);

4.

var response = await axios({
"method": "post",
"url": "https://api.monzo.com/oauth2/token",
"data": data
);

5.

const qs = require('qs');
var response = await axios({
"method": "post",
"url": "https://api.monzo.com/oauth2/token",
"data": qs.stringify(data),
"headers" : {
    "Content-Type": 'application/x-www-form-urlencoded'
}
);

我不断收到同样的错误:400 Bad Request Your request has missing arguments or is malformed.,除了据我所知,我没有遗漏的参数,也没有格式错误。通过在线阅读,错误表明 axios 没有通过dataPOST 请求正确发送,但我会感谢任何人提供的任何见解。

由于我无法控制要发送到的 API,有没有办法验证 axios 发送了什么?

我的任何请求都应该有效吗?

提前致谢

标签: javascriptnode.jsoauth-2.0axios

解决方案


推荐阅读