Home > Blockchain >  Is possible to save data form API once, save it on a variable and display it on demand on my node JS
Is possible to save data form API once, save it on a variable and display it on demand on my node JS

Time:01-13

Im new to node js.

const http = require('http');
const url = require('url')

http.createServer(function (req, res) {
  const { query, pathname } = url.parse(req.url, true)
  let answer =[];
  async () => {
    await fetch('https://dummyjson.com/products').then(r => r.json()).then(d => {
      answer.push(JSON.stringify(d))
    })
  }

  res.writeHead(200, {
    "Content-Type": 'text/html',
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "X-Requested-With"
  });
  res.end(answer);
}).listen(8080);

console.log('Server Started');

Im trying to save the data in my array, once i get the info i should be able to render all data from that api.

CodePudding user response:

You have several issues:

  1. Your async IIFE with the fetch() in it is never called.
  2. Even if it was called, you wouldn't be waiting for it. You are trying to send your response before the fetch() has completed.
  3. You are trying to send an array (that has JSON in it) with res.end(). You can't do that. You need to send text.
  4. You are setting the content-type to text/html, but attempting to send JSON. If you're actually going to send JSON, then set the content-type to application/json.

Change to this:

const http = require('http');
const url = require('url')

http.createServer(async function (req, res) {
  const { query, pathname } = url.parse(req.url, true)
  const answer = [ ];

  const r = await fetch('https://dummyjson.com/products');
  const data = await r.json();

  answer.push(data);

  res.writeHead(200, {
    "Content-Type": 'application/json',
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "X-Requested-With"
  });
  res.end(JSON.stringify(answer));
  
}).listen(8080);

console.log('Server Started');

Summary of Changes:

  1. The callback to http.createServer() is marked as async so we can directly use await in that callback function.
  2. Remove .then() and just use await. Don't mix await and .then(). Pick one style or the other.
  3. Push Javascript data, not JSON into the array.
  4. Call JSON.stringify() on the whole array. You can pass an array to res.end(), you have to pass text.
  5. Change content-type to application/json.
  • Related