1

I'm new to node/express. I have a simple express app with one post route ('/'). Given a list of GitHub users names, it should return information about those developers.

For example, if I post

{ "developers": ["JohnSmith", "JaneDoe"] }

It should return

[
  {
    "bio": "Software Engineer at Google",
    "name": "John Smith"
  },
  {
    "bio": "Product Manager, Microsoft",
    "name": "Jane Doe"
  }
]

This is what I have so far

const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());

app.post('/', function(req, res, next) {
  try {
    let results = req.body.developers.map(async d => {
      return await axios.get(`https://api.github.com/users/${d}`);
    });
    let out = results.map(r => ({ name: r.data.name, bio: r.data.bio }));    
    return res.send(out);
  } catch {
    next(err);
  }
});

app.use((err, req, res, next) => {
  res.send("There was an error");
})

app.listen(3000, function(){
  console.log("Server started on port 3000!");
});

When I try this in a tool like Insomnia, I keep getting There was an error.

4 Answers4

1

The way you return JSON in an Express API is as follows:

res.status(200).json(out)

See https://expressjs.com/it/api.html for the full documentation.

Mattia Rasulo
  • 1,236
  • 10
  • 15
0

You can use res.formate() as per this docs...

Or set type for res as per this Docs...

res.type('json')
JeX
  • 95
  • 1
  • 10
0

From middleware, you are always saying res.json("there is some error"), why are you keeping it there if not needed. if you remove app.use(). you will see the request is returning you names of the developer

read this for error handling. https://expressjs.com/en/guide/error-handling.html

0

You're getting There was an error. Because, there is an error in your / route. But, the thing is you haven't wrote the err parameter with catch. If add that one in your catch (of your try/catch block) and console.log it, you'll see the error

TypeError: Cannot read property 'name' of undefined

You're getting this error because, results variable is actually an array of pending Promise. You need to first resolve these pending promises. One way to do is,

app.post("/", function (req, res, next) {
  try {
    const developers = req.body.developers;
    let promises = [];
    developers.map((d) => {
      promises.push(axios.get(`https://api.github.com/users/${d}`));
    });

    Promise.all(promises).then((responses) => {
      let out = responses.map((r) => ({
        name: r.data.name,
        bio: r.data.bio,
      }));

      return res.send(out);
    });
  } catch (err) {
    next(err);
  }
});
Viral Patel
  • 1,104
  • 4
  • 7