Skip to content

Integrating With Express

Amir Yasin edited this page Feb 8, 2015 · 2 revisions

If you want to try out frhttp but aren't ready to convert just yet, or you have an existing Express/Connect project that you want to move over slowly, you can try out frhttp on one or a few routes. Doing so is very easy.

A simple example

This assumes you have set up Express and frhttp via npm

'use strict';

//create an frhttp server

var frhttp = require('frhttp').createServer();

//configure a route
frhttp.GET('/').onValue(function (route) {
    route.render({
        params: [],
        fn: function(writer) {
            writer.writeBody('Hello world!');
        }
    });
});

//configure express

var express = require('express');
var app = express();
var port = 3000;

// here it is, just one line.
app.get('/', frhttp.runRoute);


/*
 * Start it up
 */
app.listen(port);
console.log('Express started on port ' + port);

We're intentionally using a very simple frhttp route here. If you want to understand how to configure complex routes, you should take a look at the when documentation.

Once we've set up a route, the simplest way to run it is to call runRoute on the server with the request and response from the express route. The frhttp server will handle everything else beyond this point.

Get More Control

For more advanced usage, replace the following line in the previous example:

frhttp.runRoute(request, response);

with the following:

var url = require('url').parse(request.url);
var tap = frhttp.TAP_GET(url);
if (tap) {
    tap.onValue(function (executor) {
        executor.execute(url, request, response, executor.inject);
    });
}
else {
    response.end();
}

While most use cases will not require it, this method allows the caller to control the URL in case the configured frhttp endpoints are differently named from the Express ones. It also allows you to add injected values prior to calling the executor. To add injected values simply do the following:

executor.inject['yourInjectedValuesName'] = 'the value';

Clone this wiki locally