[英]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.