I want to add a custom 404 page in Deno's http/file_server.ts

Asked 1 years ago, Updated 1 years ago, 20 views

I am writing a file server in Deno, but how can I add a custom 404 page?

javascript deno

2022-09-30 13:52

1 Answers

I don't think this is the best solution, but if you simply use serveDir, the response#status has 404, so you can use custom 404 by returning any custom response instead.

import {serve} from "https://deno.land/[email protected]/http/server.ts";
import {serveDir} from "https://deno.land/[email protected]/http/file_server.ts";
import {
  Status,
  STATUS_TEXT,
} from "https://deno.land/[email protected]/http/http_status.ts";

serve(async(req)=>{
  constres = wait serveDir(req, {
    fsRoot: "./static/",
    showDirListing: true,
  });
  if(res.status===Status.NotFound){
    return new Response("404 not found", {
      status —Status.NotFound,
      statusText:STATUS_TEXT [Status.NotFound],
      headers:{
        "content-type": "text/html",
      },
    });
  }
  return res;
});


2022-09-30 13:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.