如何在deno的特定路径上返回html文件?



我有一个非常基本的deno应用程序与oak模块来构建http服务器。我想发送一个http文件,index.html,只有当路径是/(不是/anyotherpath)。从橡树的github我有这个代码

app.use(async (ctx, next) => {
try{
await ctx.send({
root: `${Deno.cwd()}/public`,
index:"index.html",
});
}catch{
await next();
}
});

但是我如何只发送给定路径的html ?我也尝试了Router但是我不知道如何提供html文件。

如果想要用index.html文件响应,并且只有在根路径/下,您可以这样做:

我在服务器示例的几乎每一行都包含了注释。如果有不清楚的地方,请在评论中提出任何问题。请务必参考Oak文档。

./public/index.html:

<!doctype html>
<html lang="en">
<head>
<title>Hello world</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>

./main.ts:

import * as path from "https://deno.land/std@0.146.0/path/mod.ts";
import { Application, Router } from "https://deno.land/x/oak@v10.6.0/mod.ts";
// The directory of this module
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
// The public directory (with "index.html" in it)
const publicDir = path.join(moduleDir, "public");
// A helper function to get the file contents
// of a specific file path in the public directory
function getPublicFile(...filePath: string[]): Promise<Uint8Array> {
return Deno.readFile(path.join(publicDir, ...filePath));
}
// Create a router
const router = new Router();
// Only handle GET requests to the "/" path
router.get("/", async (ctx, next) => {
// Set the contents of the "index.html" file to the response body
ctx.response.body = await getPublicFile("index.html");
// Set the appropriate resopnse type for HTML
ctx.response.type = "text/html";
// This isn't technically needed here, but it's good practice
// because other middleware might need to run in more complicated routes
await next();
});
// Create the app
const app = new Application();
// Use the router from above
app.use(router.routes());
app.use(router.allowedMethods());
// This is not needed, but is potentially nice for yourself in the console
function printStartupMessage({ hostname, port, secure }: {
hostname: string;
port: number;
secure?: boolean;
}): void {
const address = new URL(
`http${secure ? "s" : ""}://${
hostname === "0.0.0.0" ? "localhost" : hostname
}:${port}/`,
).href;
console.log(`Listening at ${address}`);
console.log("Use ctrl+c to stop");
}
// Run the function above when the server starts listening
app.addEventListener("listen", printStartupMessage);
// Start the server
await app.listen({ port: 8000 });
% deno run --allow-net --allow-read main.ts        
Listening at http://localhost:8000/
Use ctrl+c to stop

http://localhost:8000/的请求将使用上面的index.html文件响应,所有其他路由将使用404 Not Found响应。

最新更新