0

I am trying to export some REST API functions out of a module. I am using node.js restify.

I have a file called rest.js which contains the API.

module.exports = {
    api_get: api_get,
    api_post: api_post,
};

 var api_get= function (app) {
    function respond(req, res, next) {
        res.redirect('http://127.0.0.1/login.html', next);
        return next();
    }; //function respond(req, res, next) {

    // Routes
    app.get('/login', respond);
} 

var api_post= function (app) {
    function post_handler(req, res, next) {
    }; 

    app.post('/login_post', post_handler);    
} 

The APIs are called in this manner;

var rest = require('./rest');

var server = restify.createServer({
    name: 'myapp',
    version: '1.0.0'
});

rest.api_get(server);
rest.api_post(server);

The error encountered is TypeError: rest.api_get is not a function

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

1 Answers1

1

Your mistake was to export the function variables before they were defined. The correct way is do the export at the bottom. It is also good practice to do it this way all the time. THe correct code would look like this;

 var api_get= function (app) {
    function respond(req, res, next) {
        res.redirect('http://127.0.0.1/login.html', next);
        return next();
    }; //function respond(req, res, next) {

    // Routes
    app.get('/login', respond);
} 

var api_post= function (app) {
    function post_handler(req, res, next) {
    }; 

    app.post('/login_post', post_handler);    
}  

module.exports = {
    api_get: api_get,
    api_post: api_post,
};
guagay_wk
  • 26,337
  • 54
  • 186
  • 295