无法在Node.js中交换访问令牌的代码.Mailchimp API.



我正在尝试将OAuth2与Mailchimp API一起使用,并且我正在遵循他们的文档,但我无法完成步骤4。在此步骤中,我将从授权屏幕收到的代码交换为令牌。根据文档,这可以在 curl 中完成,如下所示:

curl --request POST 
--url 'https://login.mailchimp.com/oauth2/token' 
--data "grant_type=authorization_code&client_id={client_id}&client_secret={client_secret}&redirect_uri={encoded_url}&code={code}" 
--include

我试图通过编写以下内容将其转换为在节点上工作.js:

var dataString = 'grant_type=authorization_code&client_id=' + clientid + '&client_secret=' + clientsecret + '&redirect_uri=' + encodedurl + '&code=' + url.parse(req.url, true).query.code;
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
data: dataString
};
function callback(error, response, body) {
if (!error) {
console.dir(JSON.stringify(body));
}
else{
console.dir(error); 
}
}
request(options, callback);

当我发出request.debug = true时,我看到我收到400错误。发送到控制台的消息是一堆乱码。但是,当我使用这些相同的变量和端点通过Postman进行身份验证时,它工作正常,因此问题不在于变量或API本身。

我不完全确定我在这里做错了什么。我提出的请求似乎与文档中用 curl 编写的请求几乎相同。那么我哪里出错了呢?

嗯,你忘了定义request吗?

var request = require("request");

终于想通了。问题出在请求的标头中。有两种方法可以解决此问题。首先是使用"表单"而不是"数据"。如果使用"form"选项,请求将自动包含"内容类型:x-www-form-urlencoded"标头。

var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
form: dataString
};

我不确定在使用"data"选项时使用什么标题,或者根本没有声明内容类型。无论哪种方式,如果选择继续使用"data"选项,都可以手动声明内容类型标头。这是第二种可能的解决方案。

var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers: 
{ 'Content-Type': 'application/x-www-form-urlencoded' },
body: dataString
};

经过多次尝试,我明白了。只能使用一次代码。因此,请确保仅使用一次从重定向 URI 获取的代码。

使用新代码使用此代码

const dataString = "grant_type=authorization_code&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&code="+req.body.code
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
},
form: dataString
};
function callback(error, response, body) {
if (!error) {
let str = JSON.stringify(body)
res.setHeader("Content-Type", "application/json; charset=utf-8")
res.send(body)
}
else{
console.dir(error);
res.send(error)
}
}
request(options, callback);

最新更新