我正在学习nodejs并尝试进行API调用。该API使用JWT进行身份验证。
我创建了以下功能来对令牌进行签名:
function token() {
const payload = {
iat: Math.floor(new Date() / 1000),
exp: Math.floor(new Date() / 1000) + 30,
sub: "api_key_jwt",
iss: "external",
jti: crypto.randomBytes(6).toString("hex")
};
return new Promise((resolve, reject) => {
jwt.sign(payload, privatekey, { algorithm: "RS256" }, function(
err,
token2
) {
if (err) reject(err);
else resolve(token2);
});
});
}
exports.genToken = async function() {
const header = {
"x-api-key": api
};
const data = {
kid: api,
jwt_token: await token()
};
async function authorization(req, res) {
try {
const auth = await rp({
url: authurl,
method: "POST",
headers: header,
body: data
});
res.send(auth.body);
} catch (error) {
res.send(404).send();
}
}
return {
"x-api-key": api,
Authorization: "Bearer " + authorization()
};
};
这很好。然后,我创建了一个函数来进行API调用:
const token = require("./index").genToken;
const rp = require("request-promise");
exports.getOrderBook = function(res, error) {
const full_url = url + "order_book";
const auth = token();
rp({
url: full_url,
method: "GET",
headers: auth,
body: {
market: "btceur"
},
json: true
})
.then(function(response) {
res(response);
})
.catch(function(err) {
error(err);
});
};
我用Express
称呼它:
routes.get("/orderbook", async (req, res, next) => {
try {
const book = await orders.getOrderBook();
res.send(book);
} catch (error) {
next(error);
}
});
但是,当我调用我的API时,它在控制台中显示错误:
TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是以下其中一个 输入字符串或缓冲区。收到类型对象。
我猜想错误与令牌生成有关,因为如果我在console.log(auth)
函数中getOrderBook
表示Promise { <pending> }
,那么很可能将对象作为jwt令牌传递
这真的是问题吗?我尝试了很多在Internet上找到的不同解决方案,但是Async/Await
的概念对我来说是陌生的,我很难弄清楚。
非常感谢大家!
答案 0 :(得分:0)
由于getToken
是anync
函数,因此返回值也包装在Promise
中,因此您将需要另一个anync/await
:
exports.getOrderBook = async function() {
let response;
try {
const full_url = url + "order_book";
const auth = await token();
response = await rp({
url: full_url,
method: "GET",
headers: auth,
body: {
market: "btceur"
},
json: true
});
} catch (e) {
// handle error
throw e
// or console.error(e)
}
return response;
};
在此行Authorization: "Bearer " + authorization()
中,authorization
也在返回诺言
const bearer = await authorization()
return {
"x-api-key": api,
Authorization: "Bearer " + bearer
};
要进行错误处理,请将整个内容包装在try..catch
块中
exports.genToken = async function() {
try {
const header = {
"x-api-key": api
};
const data = {
kid: api,
jwt_token: await token()
};
async function authorization(req, res) {
let auth;
try {
auth = await rp({
url: authurl,
method: "POST",
headers: header,
body: data
});
// res object not available
// res.send(auth.body);
} catch (error) {
// res object not available, better throw error and handle in your middleware
// res.send(404).send();
}
return auth
}
const bearer = await authorization()
} catch (e) {
// handle error
}
return {
"x-api-key": api,
Authorization: "Bearer " + bearer
};
}