Skip to main content

Binding To Node.Js Server

Handlers contain the logic of your application. Handlers are executed when a client sends a request only after you bind them to a server. Http4ts is server independent, meaning that it is possible to connect a handler to almost every library or platform which can listen to http requests. Http4ts supports binding to Node.Js out-of-the-box.

To bind your handler to Node.Js, create an http or https server and use toNodeRequestListener to bind it to an http4ts handler:

import { HttpRequest, HttpStatus, toNodeRequestListener, res } from "http4ts";
import * as http from "http";
async function handler(req: HttpRequest) {  return res({    body: "Hello world!",    status: HttpStatus.OK  });}
const server = http.createServer(toNodeRequestListener(handler));//                                    ^---This is where the binding takes placeconst hostname = "127.0.0.1";const port = 3000;
server.listen(port, hostname, () => {  console.log(`Server running at http://${hostname}:${port}/`);});

If you want to create an https server, just import the https module. If you want to configure your server differently, you just need to learn how to configure a Node.Js server. Http4ts requires no library-specific configuration!