Márcio
Márcio

Reputation: 181

How to display an API in the browser? How to migrate that request-promise code into a node-fetch code?

I'm requesting data from Coinmarketcap API, I know how to display it on terminal, but I don't know how to show it on the browser, how could I do that?

Here is my code:

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '1',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' // it isn't my real api key
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response.data[0].quote.USD.price);
}).catch((err) => {
  console.log('API call error:', err.message);
});

I don't know how to migrate that request-promise code into a node-fetch code, how could I do that?

Upvotes: 0

Views: 247

Answers (1)

Prabhjot Singh Kainth
Prabhjot Singh Kainth

Reputation: 1861

Just try this code, assuming you are using Express JS :

To install node-fetch use following command:

npm install --save node-fetch

And then use this code:

const express = require('express');
const app = express();
const fetch = require('node-fetch');
app.get('/', function(req, res, next) 
{
    var url ='https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
    var headers = 
    {
        "Content-Type": "application/json",
        "X-CMC_PRO_API_KEY": "b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c"
    }
    var data = 
    {
        'start': '1',
        'limit': '1',
        'convert': 'USD'
    }
    fetch(url, { method: 'GET', headers: headers, body: data})
    .then((result) => 
    {
        return result.json();
    })
    .then((json) => 
    {
        res.send(json);   
    });
}

Upvotes: 1

Related Questions