![](/img/trans.png)
[英]Node.js Axios POST request with application/x-www-form-urlencoded format?
[英]x-www-form-urlencoded format - using https in node.js
我目前正在写入 API 以尝试获取令牌。 我快到了,但在最后一个障碍中倒下了..
const fs = require('fs');
const https = require('https');
const ConfigParams = JSON.parse(fs.readFileSync('Config.json', 'utf8'));
const jwt = require('jsonwebtoken');
const apikey = ConfigParams.client_id;
var privateKey = fs.readFileSync(**MY KEY**);
var tkn;
const jwtOptions = {
algorithm: 'RS512',
header: { kid: 'test-1' }
}
const jwtPayload = {
iss: apikey,
sub: apikey,
aud: **API TOKEN ENDPOINT**,
jti: '1',
exp: 300
}
jwt.sign(jwtPayload,
privateKey,
jwtOptions,
(err, token) => {
console.log(err);
//console.log(token);
tkn = token;
let = tokenPayload = {
grant_type: 'client_credentials',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
client_assertion: tkn
}
tokenAuthOptions = {
payload: tokenPayload,
host: **HOST**,
path: **PATH**,
method: 'POST',
}
https.request(
tokenAuthOptions,
resp => {
var body = '';
resp.on('data', function (chunk) {
body += chunk;
});
resp.on('end', function () {
console.log(body);
console.log(resp.statusCode);
});
}
).end();
}
)
编码的令牌在第一部分恢复正常,但 https 请求返回了一个问题。
我得到的回复是 grant_type 丢失,所以我知道由于这个 x-www-form-urlencoded 我有格式问题,但我不知道如何解决它。
这是网站上说的:
您需要在请求正文中以 x-www-form-urlencoded 格式包含以下数据:
grant_type = client_credentials client_assertion_type = urn:ietf:params:oauth:client-assertion-type:jwt-bearer client_assertion = <您在步骤 4 中签名的 JWT> 这是一个完整的示例,作为 CURL 命令:
curl -X POST -H "content-type:application/x-www-form-urlencoded" --data \\ "grant_type=client_credentials\\ &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion="
终点
理想情况下,我想要一个使用 https 请求的解决方案,但如果不可能,我愿意接受其他解决方案。
任何帮助是极大的赞赏。
谢谢,克雷格
编辑 - 我根据以下建议更新了我的代码:
const params = new url.URLSearchParams({
grant_type: 'client_credentials',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
client_assertion: tkn
});
axios.post("URL", params.toString()).then(resp => {
console.log("response was : " + resp.status);
}).catch(err => {
console.log("there was an error: " + err);
})
但我仍然收到错误代码 400,但现在关于原因的细节较少。 (错误代码 400 有多个消息失败)
邮递员是最好的。
感谢@Anatoly 的支持,这有助于为我指明正确的方向。 我运气不好,所以第一次使用 postman,发现它有一个代码片段部分,有四种使用 node.js 实现这一点的不同方法。
Axion 的解决方案是:
const axios = require('axios').default;
const qs = require('qs');
var data = qs.stringify({
'grant_type': 'client_credentials',
'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion': tkn
});
var config = {
method: 'post',
url: '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.status));
})
.catch(function (error) {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.