Reputation: 227
I'm trying to create a route to return JSON data from a JSON-RPC API.
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. 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 .
Why am I getting this error?
Upvotes: 0
Views: 990
Reputation: 817030
Why am I getting this error?
Because client.getBalance('*', 1, function(err, balance) {
cannot be there where you put it.
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, e.g.
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?
It looks like client.getBalance
is an asynchronous function call, hence passing its return value to res.json
wouldn't work either. You have to pass the result that you get in the callback to 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.
Upvotes: 1