简体   繁体   English

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

[英]Export these REST API functions in node.js

I am trying to export some REST API functions out of a module. 我正在尝试从模块中导出一些REST API函数。 I am using node.js restify. 我正在使用node.js restify。

I have a file called rest.js which contains the API. 我有一个名为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);    
} 

The APIs are called in this manner; API是以这种方式调用的。

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 遇到的错误是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,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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