Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
How to obtain Json data from different site

So, let's say i have /api/cat/fact.js directory.
I wanna to get JSON Data from catfact.ninja

The thing is, i can't use require() or request() package, because if i used require, it would saya Couldnt Found Module..., and if i used request one, instead of returning the JSON Data that you beable to sees in catfact.ninja, it return JSON about the api, like hostname, port, which is i don't need

/API/api/cat/fact.js:

const express = require('express');
const app = express.Router();
const request = require('request')

app.use('', (req, res) => {
const src = 'https://catfact.ninja/fact';
  const facts = request({
        uri: src,
        hostname: 'catfact.ninja',
        port: 443, 
    path: '/fact',
    method: 'POST',
        json: 'fact'
    }, (error, response, body) => {
        if (error) console.log(error)
    console.log(body, '\n\n' + response.fact)
    })
        console.log(facts);
        return res.jsonp(facts)
})

module.exports = app;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are returning JSON in the wrong place. It should be returned inside of the callback function.

Here's the solution:

const express = require('express');
const request = require('request-promise')

const app = express();

app.use('', async (req, res) => {
  const src = 'https://catfact.ninja/fact';

  try {
    const response = await request({
      uri: src,
      port: 443, 
      method: 'GET',
      json: true
    })

    return res.jsonp(response)
  } catch (err) {
    return res.jsonp(err)
  }
})

function startServer() {
  const port = 3000

  app.listen(port, () => {
    console.info('Server is up on port ' + port)
  })

  app.on('error', (err) => {
    console.error(err)
    process.exit(1)
  })
}
startServer()

TIP: I suggest using request-promise npm package instead of request package as it provides async-await approach, which is cleaner. Else, you can continue using callback function as second request() function parameter.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!