Your First Handler
The handler is the heart of http4ts. An HttpHandler connects your logic code to the library. A handler is simply a function that receives a request object and should return a response object:
type HttpHandler = (req: HttpRequest) => HttpResponse | Promise<HttpResponse>;As an example, the following handler echoes the request body to the response:
async function handler(req: HttpRequest /* 1 */) { return res({ /* 2 */ status: HttpStatus.OK, body: req.body /* 3 */ });}- The handler receives a request object
- It should return a response object.
resis a helper function that creates a response object. - The request object has fields and methods to read and manipulate it. The three most important request object fields are
body,headers, andmethod. Here we passedbodyto response.
note
A handler should bind to a server in order to be used. You will learn about binding to server in the next article.