1

I'm making a simple API in express js. I've an end point where I'll make a call to GitHub api int turn. My Front-end application will utilize it. Here is my code:

api.js

const express = require('express');
const router = express.Router();
...
var http = require('http');
var https = require("https");

router.get('/github', function (req, res) {

    // APPROACH 1: Failed : fetch is not defined
    // fetch('https://api.github.com/users/tmtanzeel')
    //     .then(response => response.json())
    //     .then(json => console.log(json))


    // APPROACH 2: Failed : throw er; // Unhandled 'error' event
    /*try {
        https.get('https://api.github.com/users/tmtanzeel',function (res) {
            console.log(res);
        })
    } catch (error) {
        ...
    }*/
});

Both my approaches are failing. I've almost no experience with Express. Please picth in

Tanzeel
  • 4,174
  • 13
  • 57
  • 110

3 Answers3

1

The second method is almost corrent. Add the error handler and send to the caller the data you just received.

https.get('https://api.github.com/users/tmtanzeel',function (apiRes) {

  apiRes.pipe(res);

}).on('error', (e) => {

      console.error(e);
      res.status(500).send('Something went wrong');
});

Handling the response (stream) received from the API call can be done in two ways.

  1. Using pipes which is automatic
  2. Handle read events and manage the data writing manually

I have used the first approach.

However, it is very well recommended that you get sound knowledge in handling Streams if you use Node JS. Streams are the basis of Node JS requests and responses.

https://nodejs.dev/learn/nodejs-streams

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    very well explained. Thanks for your time. This worked. – Tanzeel Oct 01 '21 at 16:35
  • I'm using your solution in the production. I'm facing other (unrelated issues) Can you plz look into this: https://stackoverflow.com/questions/69409586/how-to-make-a-get-call-to-api-github-with-express-server – Tanzeel Oct 01 '21 at 17:04
  • I'm asking your help because youve good knowledge in this field. – Tanzeel Oct 01 '21 at 17:04
0

You should use Express to handle incoming requests. (for example if your webapp fetches data from your (express) server). Read the docs: http://expressjs.com

Your first attempt failed because fetch is an implementation of the web-browser, not one of nodejs.

If you want to use fetch try: https://www.npmjs.com/package/node-fetch
its a well documented, easy to use fetch function.

Pascal K
  • 128
  • 1
  • 10
0

From your examples, all seems fine except I can't see you sending the returned data to the client.

You can try something similar like adding res.send(data) to send the data and make it available on the /github route