[英]express router.get() function SyntaxError
I'm trying to create a route to return JSON data from a JSON-RPC API. 我正在尝试创建一种从JSON-RPC API返回JSON数据的路由。
My code: 我的代码:
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);
});
});
});
It's using the npm package node-litecoin. 它使用npm包node-litecoin。 I have required it and created a client var like so:
我需要它并创建了一个客户端变量,如下所示:
var client = new litecoin.Client({
host: 'localhost',
port: 9332,
user: 'myaccount',
password: 'mypass'
});
client.getBalance('*', 1, function(err, balance) { ^ SyntaxError: Unexpected token . client.getBalance('*',1,function(err,balance){^ SyntaxError:意外的令牌。
Why am I getting this error? 为什么会出现此错误?
Why am I getting this error?
为什么会出现此错误?
Because client.getBalance('*', 1, function(err, balance) {
cannot be there where you put it. 因为
client.getBalance('*', 1, function(err, balance) {
不能放在您放置它的位置。
Lets have a closer look: 让我们仔细看看:
res.json({ ... });
The {...}
here indicate an object literal . 这里的
{...}
表示对象文字 。 The "content" of the literal has to be a comma separated list of key: value
pairs, eg 文字的“内容”必须是逗号分隔的
key: value
对列表,例如
res.json({foo: 'bar'});
You instead put a function call there: 您改为在此处放置函数调用:
res.json({ client.getBalance(...) });
which simply is invalid. 这根本是无效的。
How can I have the route
'/balance'
output theclient.getBalance()
function?我如何让路由
'/balance'
输出client.getBalance()
函数?
It looks like client.getBalance
is an asynchronous function call, hence passing its return value to res.json
wouldn't work either. 看起来
client.getBalance
是一个异步函数调用,因此将其返回值传递给res.json
也不起作用。 You have to pass the result that you get in the callback to 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);
});
});
If you are not very familiar with JavaScript's syntax, I recommend to read the MDN JavaScript Guide . 如果您不太熟悉JavaScript的语法,建议阅读MDN JavaScript Guide 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.