Skip to main content
Module

x/fastro/examples/middleware.ts

Fast and simple web application framework for deno
Go to Latest
File
import { Fastro } from "../mod.ts";const server = new Fastro();
// MIDDLEWARE is used to add a new property or function to `Request` object//// setup global middleware// all changes are available for all routesserver .use((req) => { req.root = "root:"; }) .use((req) => { req.greeting = "hello"; }) .use((req, done) => { req.name = "world"; // if you have multiple middleware in a route // and dont send anything, you must call 'done callback' once. done(); }) .get("/", (req) => { const msg = req.root + req.greeting + "," + req.name; req.send(msg); }) .get("/hi", (req) => { const msg = "hi:" + req.root + req.greeting + "," + req.name; req.send(msg); });
// you can also send a response via a middleware// this will handle all http methods (GET, POST, PUT, DELETE)// no need call a callback here, because you already send a responseserver.use("/send", (req) => { req.send("send from middleware");});
// setup middleware for `/hello` route// all changes only available for this routeserver .use("/hello", (req) => { if (req.url === "/hello") return req.send("hello middleware"); req.hello = "hello"; }) // if you already send a response from the middleware // this line will not be called .get("/hello", (req) => { req.send(req.hello); });
await server.listen({ port: 3000 });