In the last post we used the Cavia to create the first endpoint, today we will use this micro framework to parse the request body.
Step 1: Installation
First, let's install the @caviajs/http-body
package, which enables parsing.
npm install @caviajs/http-body --save
Step 2: New endpoint
Create a new endpoint whose method is POST
, PUT
or PATCH
.
import { Route } from '@caviajs/http-router';
import { HttpBody } from '@caviajs/http-body'; // 👈
export const GuineaPigCreateRoute: Route = {
handler: async (request, response): Promise<void> => {
const body = await HttpBody.parse(request, 'json'); // 👈
console.log(body);
},
method: 'POST', // 👈
path: '/guinea-pigs',
};
The created endpoint add to HttpRouter
instance.
import http from 'http';
import { HttpRouter } from '@caviajs/http-router';
import { GuineaPigCreateRoute } from './routes/guinea-pig-create-route'; // 👈
(async () => {
const httpRouter: HttpRouter = new HttpRouter();
httpRouter
.route(GuineaPigCreateRoute); // 👈
const httpServer: http.Server = http.createServer((req, res) => {
httpRouter.handle(req, res);
});
httpServer.listen(8080, () => {
console.log(`Http server listening at port ${8080}`);
});
})();
Step 3: Start server
Start the server using the terminal.
npx ts-node app/web.ts
Step 4: Make request
Make a request to our newly created endpoint.
curl -XPOST -H "Content-type: application/json" -d '{"name":"Hello World"}' 'http://localhost:8080/guinea-pigs'
It's all for today! I hope this short post was helpful to you.
See you!
Top comments (0)