在node.js中导出这些REST API函数

时间:2015-12-25 16:19:46

标签: javascript node.js rest export restify

我正在尝试从模块中导出一些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

1 个答案:

答案 0 :(得分: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,
};