Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda