Reputation: 653
I am kinda new to this node js thing. So, please bear with me.
I have got a json string array in dotNetFin.js. I am not sure as to why error comes up(when i switch over to About page), and, in the command prompt window, it shows up "Undefined is not a function"
Also, everything works fine if I include that json array in app.js.
Well here is my code:
app.js
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.render('home');
});
var teamData = require('./dotnetFin.js');
app.get('/about', function (req, res) {
res.render('about', { dotnet: teamData.getTeamData() });
});
//custom 404 page
app.use(function (req, res) {
res.type('text/plain');
res.status(404);
res.send('404 Not Found');
});
app.use(function (err, req, res, next) {
console.log(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 Server Error');
});
app.listen(app.get('port'), function () {
console.log('Express started on server' + app.get('port'));
});
var handleBars = require('express3-handlebars').create({ defaultLayout: 'main' });
app.engine('handlebars', handleBars.engine);
app.set('view engine', 'handlebars');
dotnetFin.js
var dotnetTeam = ["V",
"M",
"A",
"H",
"A",
"G",
"K"];
var getTeamData = function () {
return dotnetTeam;
};
main.handlebars
<!doctype html>
<html>
<head>
<h2>Fin</h2>
</head>
<body>
{{{body}}}
</body>
</html>
about.handlebars
<h1>About Fin</h1>
<h2>Dotnet Team</h2>
<h3>{{dotnet}}</h3>
Error Snapshot:
Upvotes: 3
Views: 49642
Reputation: 3316
You need to export your getTeamData
function from dotnetFin.js file. So just replace
var getTeamData = function () {
return dotnetTeam;
};
with
exports.getTeamData = function () {
return dotnetTeam;
};
and your API should work.
You always need to export variables or methods from your node module (.js file) in order to be able to access them from some other file which requires that module.
Upvotes: 4
Reputation: 3106
require
does not simply include the file, like for example include
in C/C++. There is an own API for modules that can then be require
d, however your case can be solved a lot easier by just changing your dotnetFin.js
file to a pure json file:
dotnetFin.json:
["V",
"M",
"A",
"H",
"A",
"G",
"K"]
and then just requiring that file:
var dotnetFin = require('./dotnetFin.json')
Now dotnetFis
contains the array defined in the file.
Upvotes: 1