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')-%>
CodePudding user response:
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});
});
CodePudding user response:
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);
});
});