Reputation: 4526
I am trying to fetch API data using Node JS. I am using this node package to do so.
https://www.npmjs.com/package/cryptocompare
The documentation of that package is easy enough.
global.fetch = require('node-fetch')
const cc = require('cryptocompare')
cc.price('BTC', ['USD', 'EUR'])
.then(prices => {
console.log(prices)
})
.catch(console.error)
I've tested it with npm.runkit.com and it works.
However, when I install the package into my app, I don't see any output in the console.
I am using JetBrains WebStorm and these are the steps I've taken.
Then within /routes/index.js
I added the following
var express = require('express');
var router = express.Router();
global.fetch = require('node-fetch');
const cc = require('cryptocompare');
/* GET home page. */
cc.price('BTC', ['USD'])
.then(prices => {
console.log(prices)
}).catch(console.error);
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Example'
});
});
module.exports = router;
But that displays nothing in the console log. I tried moving the global.fetch
to app.js
in the root directory but that didn't do anything either.
What am I doing wrong here?
Upvotes: 1
Views: 3312
Reputation: 1554
var express = require('express');
var router = express.Router();
global.fetch = require('node-fetch');
const cc = require('cryptocompare');
/* GET home page. */
router.get('/', function(req, res, next) {
cc.price('BTC', ['USD'])
.then(prices => {
res.render('index', {
title: prices
});
}).catch(console.error);
});
module.exports = router;
This will work for you
Upvotes: 2
Reputation: 1554
Not sure why you are not getting anything. I tried with same steps and got the result.
I just did one thing differently, i pasted whole code in a file named as abc.js.
and then i ran it in command line like this
node abc.js
and i got this result
{ USD: 2797.06 }
Can you please try it again because its working awesome for me. Let me know if you face any problem.
Continue...
So if you want to use it in index.js then you can do something like this
cc.price('BTC', ['USD'])
.then(function(prices){
console.log(prices)
}).catch(function(error){
console.log(error);
});
I just changed its syntex from es6 to es5
Upvotes: 1