0

How Can I write API methods in node.js express 3 application. My app.js looks like:

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'));
});

I am using html view engine, please help as I am a newbie here.

Saurabh Sashank
  • 280
  • 1
  • 5
  • 18

1 Answers1

1

Just to give you idea see following way:

routes.js | Keep single route.js or create multiple files for different routes depending on functionality

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 folder will contain files like comment.js, inbox.js .. these files contain api methods, write logic here

//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 | It can be in app.js or can be in some other route-config file and that file could be required in app.js, its again upto you what to choose

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

Edit For beginners to get up and running Github Repo | Basic api methods using express.js download and run node app.js

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57