Search code examples
node.js

Node JS: 500 Server Error


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:

enter image description here

enter image description here


Solution

  • 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.