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

402
Vistas
when res.render() method used, internal express server response error with status code 500

I am new to Node.js so please be patient with me. I am experiencing difficulties with an Express server.

My goal is to make GET request and load the data from external server and render it on my website. I successfully load the data from the external server and parse it into JS object. When I console.log it, I can see the JS object is correctly transformed. But when I render it on my ejs file, it says that the array I passed is undefined. I spelled correctly variables names. When I inspect it by using developer tools and I get this error message in the console:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

This is the code I have:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static(__dirname + "/public"));

// const ejs = require("ejs");

const https = require('https');

app.get("/Health",function(req, res) {

  let healthUrl = "https://newsapi.org/v2/top-headlines/?category=health&apiKey=API_KEY&language=en";

  https.get(healthUrl, (resp) => {
    let data ='';
    resp.on("data",(chunk)=>{
      data += chunk;
    });

    resp.on("end",() => {

        let newData =  JSON.parse(data);
        let allArticles = newData.articles;
    });

    }).on('error', (e) => {
        console.error(e);
    });
    res.render("Health",{allArticles:allArticles});
});

when I console.log(allArticles) in app.js file, I can see the javascript that I loaded. But when I render it on ejs file, error occurred and got the message that "allArticles is undefined" I checked it in ejs file like below:

<%-include('partials/header')-%>

<% console.log(allArticles) %>

<%-include('partials/footer')-%>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

you are trying to access allArticles variable outside its scope Try returning res.render where you have declared allArticles variable Solution will be below -

    app.get("/Health", function (req, res) {
      let healthUrl =
        "https://newsapi.org/v2/top-headlines/category=health&apiKey=5ad38a0db6944d22aa81b5420f6a62f4&language=en";
      https
        .get(healthUrl, (resp) => {
          let data = "";
          resp.on("data", (chunk) => {
            data += chunk;
          });
          resp.on("end", () => {
            let newData = JSON.parse(data);
            let allArticles = newData.articles;
            // returning response where allArticles declared
            return res.render("Health", { allArticles: allArticles });
          });
        })
        .on("error", (e) => {
          console.error(e);
        });
    });
    
        
about 4 years ago · Juan Pablo Isaza Denunciar

0

Variables in javascript are scoped. You declare it with let inside this block:

 resp.on("end",() => {

    let newData =  JSON.parse(data);
    let allArticles = newData.articles;
});

and therefore can not used it outside that block. To fix it try declaring the variable outside and assigning inside. Like this:

let allArticles;
resp.on("end",() => {

    let newData =  JSON.parse(data);
    allArticles = newData.articles;
});

However you probably only want to render the page if no error occurred, so try moving the render line inside this block, like this:

 resp.on("end",() => {

    let newData =  JSON.parse(data);
    let allArticles = newData.articles;
    res.render("Health",{allArticles:allArticles});
});
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