【问题标题】:Export these REST API functions in node.js在 node.js 中导出这些 REST API 函数
【发布时间】:2015-12-26 00:36:44
【问题描述】:

我正在尝试从模块中导出一些 REST API 函数。我正在使用 node.js restify。

我有一个名为 rest.js 的文件,其中包含 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);    
} 

API 以这种方式调用;

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

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

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

遇到的错误是TypeError: rest.api_get is not a function

【问题讨论】:

    标签: javascript node.js rest export restify


    【解决方案1】:

    您的错误是在定义函数变量之前导出了它们。正确的方法是在底部进行导出。一直这样做也是一个好习惯。正确的代码如下所示;

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

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 2015-02-11
      • 2016-08-26
      • 1970-01-01
      • 2021-08-14
      • 2016-09-22
      • 2019-10-28
      • 2018-03-24
      • 1970-01-01
      相关资源
      最近更新 更多