[英]How to export a local function within an Express router.get() function?
[英]express router.get() function SyntaxError
我正在嘗試創建一種從JSON-RPC API返回JSON數據的路由。
我的代碼:
router.get('/balance', function(req, res, client) {
res.json({
client.getBalance('*', 1, function(err, balance) {
if(err)
console.log(err);
else
console.log('Balance: ', balance);
});
});
});
它使用npm包node-litecoin。 我需要它並創建了一個客戶端變量,如下所示:
var client = new litecoin.Client({
host: 'localhost',
port: 9332,
user: 'myaccount',
password: 'mypass'
});
client.getBalance('*',1,function(err,balance){^ SyntaxError:意外的令牌。
為什么會出現此錯誤?
為什么會出現此錯誤?
因為client.getBalance('*', 1, function(err, balance) {
不能放在您放置它的位置。
讓我們仔細看看:
res.json({ ... });
這里的{...}
表示對象文字 。 文字的“內容”必須是逗號分隔的key: value
對列表,例如
res.json({foo: 'bar'});
您改為在此處放置函數調用:
res.json({ client.getBalance(...) });
這根本是無效的。
我如何讓路由
'/balance'
輸出client.getBalance()
函數?
看起來client.getBalance
是一個異步函數調用,因此將其返回值傳遞給res.json
也不起作用。 您必須將在回調中獲得的結果傳遞給res.json
:
router.get('/balance', function(req, res) {
client.getBalance('*', 1, function(err, balance) {
if(err)
console.log(err);
else
console.log('Balance: ', balance);
res.json(balance);
});
});
如果您不太熟悉JavaScript的語法,建議閱讀MDN JavaScript Guide 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.