简体   繁体   中英

Export these REST API functions in node.js

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

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,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM