praveenkrishp praveenkrishp - 5 months ago 7
Node.js Question

Nodejs modular programming, json error

I am new to Nodejs. I am actually writing a code to just display a name on my browser window. There are basically 4 files config.js, rootstudent.js, servicestudent.js and sqlstudent.js. I tried the approach of splitting the coe because I had read that when doing big projects its advised to split up the code.

here is my config.js

var express = require('express');
var route=require('./routestudent');
var app = express();
var port = 5000;
route.studentRoutes(app);
var server = app.listen(port, function () {
console.log('Server is running on port '+port);
});


routestudent.js

var express = require('express');
var service=require('./servicestudent');
module.exports={
studentRoutes:function(app){
app.get('/allData',function(request,response){
service.getAllData(function(records){
response.json({data:records.data});
});
});
}
}


servicestudent.js

var express = require('express');
var sql=require('./sqlstudent');
module.exports={
getAllData:function(records){
return (sql.fetchData());
}
}


sqlstudent.js

module.exports={
fetchData:function(err){
if(err)
console.log(err);
else{
return json({name : " praveen "});
}
}
}


I am also attaching the error I got in browser window error message

Kindly help in identifying, where I have gone wrong..

Answer

routestudent.js

var express = require('express');
var service=require('./servicestudent');
module.exports={
studentRoutes:function(app){
    app.get('/allData',function(request,response){
        service.getAllData(function(records){
            response.status(200).send({data:records});
        });
    });
 }
}

servicestudent.js

var express = require('express');
var sql=require('./sqlstudent');
module.exports={
    getAllData:function(cb){
        cb(sql.fetchData());
    }
}

sqlstudent.js

module.exports={
    fetchData:function(err){
        if(err)
         console.log(err);
        else{
            return {name : " praveen "};
        }
    }
}

Change your code like this.

Comments