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// you can also send a response via middleware//// setup middlewareserver // this is example for `/hi` path that send a response .use("/hi", (req) => { req.send("hi"); }) // if you do not send any response in a path, // you must call `done()` // // `done()` callback is used to forward // next step to `/hello` route handler .use("/hello", (req, done) => { req.hello = "hello"; done(); }) // if you have multiple middleware in a path // you have to call `done()` function once // this is example for `root` path: .use((req) => { req.root = "root:"; }) .use((req) => { req.greeting = "hello"; }) .use((req, done) => { req.name = "world"; done(); }) // in a middleware you can not call `done()` // and send a response in the same time // this example does not works .use("/notworking", (req, done) => { req.send("not work"); done(); }) // this example works .use("/working", (req, done) => { if (req.url === "/working") { return req.send("work"); } done(); });
// setup routeserver .get("/", (req) => { const msg = `${req.root} ${req.greeting} ${req.name}`; req.send(msg); }) .get("/hello", (req) => { const msg = `${req.hello}`; req.send(msg); });
await server.listen({ port: 3000 });