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

Export these REST API functions in node.js

本文关键字:REST API 函数 node js      更新时间:2023-09-26

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