Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How can I pass the variables exported to the second middleware (pass elements an

ID: 3743097 • Letter: H

Question

How can I pass the variables exported to the second middleware (pass elements and data_fsq from 1.js to 2.js)? how can I callback the elements and data_fsq when they receive the data from getData() function and use it in 2.js?. I keep getting undefined for both elements, and data_fsq when I try to use them in 2.js.

1.js

2.js

1 const router require('express' ).Router); 2 var fetch require('fetch-retry) 4 let data fsq ; 5 let elements -; 7 getdata(url) then (data => { router.get ('/data', function (req, res) 10 res.json (data); elements data 12 13 14 15 16 17 18 19 20 21 for (let element in data) { http -www.url,com fetch(http, f retries: 1 J) then (res if (res.ok) { return res.json(); else t throw new Error('err); 23 24 25 26 27 28 29 30 31 32 7) then(body data_fsq[data[element].id] body.items; router.get( /api/data/$fi}', function (req, res) { res.json (body) 7) .catch((error)->{ console. log ('error loading the data for· '-data_fsq [element. name); 1) 34 35 36 37 module.exports 38 39 40 router: router, data_fsq: data_fsq, // undefined elements: elements//undefined 41 42

Explanation / Answer

In node.js, every JavaScript code file is considered as a module. By default, 'module.exports' is a special object that is added in every JavaScript file in 'node.js' application.

In 'module.exports', 'module' represents the current module and 'exports' is an object that is exposed as a data object.

Let us get back to the question, to use the data exported from one module into another say 1.js to 2.js then we need to specify the module name in the require() function.

Consider the sample code as:

FILE: 1.js

let data_fsq = 'Hello';

let elements = 'World';

module.exports = {

data_fsq: data_fsq,

elements:elements

}

FILE: 2.js

var data_fsq = require('./1.js').data_fsq; //Original Code: require('./load').data_fsq;
var elements = require('./1.js').elements;   //Original Code: require('./load').elements;

console.log(data_fsq);
console.log(elements);

It seems like this is the only reason why you are not getting appropriate data values in 2.js.

Thanks for providing feedback if found appropriate.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote