Home > other >  How to obtain Json data from different site
How to obtain Json data from different site

Time:10-13

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;

CodePudding user response:

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.

  • Related