[英]How to debug a POST request to a Node.js Express application?
我是nodejs的新手,我正在使用express将我当前的API从python迁移到nodejs。
我正在尝试做的是向外部API发出请求。 我很确定我的API调用是正确的,因为我从外部API示例复制了:
exports.getBalance = function() {
return new Promise(function(resolve, reject) {
var command_url = "/v1/transaction/getBalance";
var full_url = API_URL + command_url;
var nonce = getNonce();
var data = "username=" + convertUsername(API_USER) + "&nonce=" + nonce;
const signature = makeSignature(nonce, data, command_url);
var form = {
username: API_USER,
nonce: nonce
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
var headers = {
"X-API-KEY": API_KEY,
"X-API-SIGN": signature,
"X-API-NONCE": nonce,
"Content-Length": contentLength,
"Content-Type": "application/x-www-form-urlencoded"
};
request(
{
url: full_url,
method: "POST",
headers: headers,
body: formData
},
function(error, response, body) {
if (!error) {
body = JSON.parse(body);
if (response.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
} else {
console.log("error:", error);
reject(error);
}
}
);
});
这是我的快递路线:
routes.post("/balance", mistertango.getBalance);
但是,当我尝试POST到这条路线时,我什么都没收到。 我使用Insomnia来运行API测试,因此Insomnia一直运行而没有来自我的快速API的响应。
我想知道如何调试我的代码? 我想使用Insomnia对我的快速API进行API调用,并检查我是否从我的外部API请求获得响应。
谢谢
mistertango.getBlance
返回一个Promise
但express默认不处理promises。 您需要调用res.send(data)
来实际向客户端发送响应。
routes.post("/balance", async (req, res, next) => {
try {
const balance = await mistertango.getBalance()
res.send({ balance })
} catch (error) {
next(error)
}
})
或者没有异步/等待:
routes.post("/balance", (req, res, next) => {
mistertango.getBalance()
.then(balance => res.send({ balance }))
.catch(error => next(error))
})
注1 :只要balance
不是数字,您就可以使用res.send(balance)
而不是res.send({ balance })
。 (响应主体不能是原始数字,所以我将它包装在一个对象中)。
注2 :在这两种情况下,我们都必须使用.catch
或try / catch来处理任何错误,因为express不会自己处理被拒绝的promise。 您可以使用express-promise-router来解决这个问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.