Enkhtuvshin
Enkhtuvshin

Reputation: 67

nodejs printing api response on browser

I'm absolute beginner on nodejs or javascript so excuse me for the low level question. I read a few tutorials but couldn't find a way to print out the response on the browser (i'm using ejs) what I can get is I can get it printed on console but I don't have a no clue on how to do it. Could someone direct me to the right way or show me a snippet so i can learn from it?

the way i'm getting the console log result is:

const express = require('express')
const app = express()
const bcypher = require('blockcypher')
const request = require('request');

app.set('view engine', 'ejs');

request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
  if (!error && response.statusCode == 200) {
    console.log(data)
  }
})

app.listen(3000, function() {
  console.log('listening on 3000')
})

thank you

Upvotes: 1

Views: 5204

Answers (1)

johnny_mac
johnny_mac

Reputation: 1951

So as it stands this will not display in any browser as you are not sending the data anywhere. This is your server.js file, so when the server runs, it makes the request and on successful completion, the data is logged in your console. To send it back to the browser, you would need set it up to serve requests that from the front end. A simple example:

app.get('/data', function(req, res){
  request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
    if (!error && response.statusCode == 200) {
      console.log(data)
    }
  })
  res.send('Hello browser, here's my data: ', response.body); //replace with your data here
});

Upvotes: 2

Related Questions