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

标签 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

最佳答案

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

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

关于javascript - 在node.js中导出这些REST API函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464435/

相关文章:

javascript - 等待设备并对网页提供响应

java - Rest + Spring AOP + 接口(interface)不注入(inject)

api - 如何通过Magento2上的API将商品添加到报价/购物车中

rest - 应该使用什么 URL 来更新集合中所有成员的属性

javascript - 重复小数算法

javascript - Realm React Native - SORT DISTINCT 真的有效吗?

javascript - 执行 1 分/60 秒后连接丢失

javascript - 从未调用过的 Jquery Ajax 成功函数

Javascript自动刷新表中的div

javascript - 在另一个文件中使用时找不到 module.exports 值