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