如何在node.js express 3应用程序中编写API方法。我的app.js看起来像:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var cons = require('consolidate');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
我正在使用html视图引擎,由于我是新手,请提供帮助。
为了给您一个想法,请参见以下方法:
route.js | 保留单个route.js或根据功能为不同的路由创建多个文件
var api = {}; // so that if apis grow just add like, api.inbox, api.share ..
api.comment = require('./api/comment');
exports.likeComment = function (req, res) {
api.comment.likeComment(req, res);
}
exports.unlikeComment = function (req, res) {
api.comment.unlikeComment(req, res);
}
//api object itself can be exported, its upto you what to choose
api / comment.js | api文件夹将包含comment.js,inbox.js等文件。这些文件包含api方法,请在此处编写逻辑
//method to be called when comment is liked
exports.likeComment = function (req, res) {
//code here
}
//method to be called when commend is unliked
exports.unlikeComment = function (req, res) {
//code here
}
app.js | 它可以在app.js中,也可以在其他一些route-config文件中,而该文件可能在app.js中是必需的,这取决于您选择什么
var routes = require('./routes');
//like comment api
app.post('/comment/like', function(req, res, next) {
routes.likeComment(req, res);
});
//unlike comment api
app.post('/comment/unlike', function(req, res, next) {
routes.unlikeComment(req, res);
});
编辑对于初学者来说,起步并运行Github Repo | 使用express.js的基本api方法下载并运行node app.js
乐于助人!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句