9

I am using restify building apis, it works great. But I need to render some web pages as well in the same application.

Is it possible I can use express and restify together in one application?

this is the code for restify server in app.js

var restify = require('restify');
var mongoose = require('mongoose');


var server = restify.createServer({
    name : "api_app"
});

server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
mongoose.connect('mongodb://localhost/db_name');
server.get('/', routes.index);

server.post('/api_name', api.api_name);


server.listen(8000 ,"localhost", function(){
    console.log('%s listening at %s ', server.name , server.url);
});

how do I create express server in the same app.js?

Thanks

wwli
  • 2,623
  • 6
  • 30
  • 45

5 Answers5

7

For all intents and purposes restify and express can't coexist in the same node process, because for unfortunate reasons, they both try to overwrite the prototype of the http request/response API, and you end up with unpredictable behavior of which one has done what. We can safely use the restify client in an express app, but not two servers.

durgesh.patle
  • 710
  • 6
  • 24
3

I think restify, like express, simply creates a function that you can use as a request handler. Try something like this:

var express = require('express'),
    restify = require('restify'),
    expressApp = express(),
    restifyApp = restify.createServer();

expressApp.use('/api', restifyApp); // use your restify server as a handler in express
expressApp.get('/', homePage);

expressApp.listen(8000);
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • By using restify we're trying to avoid all the overhead that comes with express. This may work, but you're just adding all that overhead back in at which point it'd be better to just implement your api and www together in express. Maybe the inverse is possible? I'd still be weary. – Cory Mawhorter Apr 16 '15 at 19:45
1

If you need REST APIs and normal web pages, I don't think you need to stick to restify any more. You can always just use express, and build your API on it instead of restify, since express can do almost all things restify does.

Munim
  • 6,310
  • 2
  • 35
  • 44
0

If you need to do a REST API and a Web application, I recommend you to use a framework that works on Express.

I created the rode framework, that is excellent to work with REST and works with Express.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
marian2js
  • 819
  • 1
  • 9
  • 10
0

I would solve this with a local api server, and a express proxy-route. Maybe not the best way with a bit of latency, but a possible solution how to separate your web frame from your api.

Peter Shaw
  • 1,867
  • 1
  • 19
  • 32