问题描述
我想知道是否可以根据 URL 更改静态资源文件。 例如,这是我的文件夹模式:
/root
-> server.ts
-> /project**s**
-> some libraries used in index.html files
-> /project1
-> index.html
-> some files used in the index.html
-> /project2
-> index.html
-> some files used in the index.html
这是如何使用 Oak 库在 deno 中处理静态文件:
app.use(async (ctx,next) => {
await send(ctx,ctx.request.url.pathname,{
root: `${Deno.cwd()}/static`,})
next()
});
我的目标是当您输入 URL 时:mydomain.com/project/project1 返回与项目 ID 对应的 index.html 文件。
现在,我正在使用 Oak 路由器来重定向这样的 URL:
const router = new Router();
router.get('/project/:project_id',project)
export const project = async (ctx: RouterContext) => {
ctx.render(`${Deno.cwd()}/project**s**/` + ctx.params.projectid + '/index.html');
}
感谢您的帮助。
解决方法
这是否回答了您的问题?
示例:动态检查现有文件夹,如果未找到,您将收到错误:No such file or directory (os error 2)
.
├── projects
│ └── foo
│ └── index.html
└── server.ts
// ./server.ts
import { Application } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
app.use(async (context) => {
await context.send({
root: Deno.cwd(),index: "index.html",});
});
await app.listen({ port: 8000 });
// ./projects/foo/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<h1>foo</h1>
</body>
</html>
deno run --allow-net --allow-read=. server.ts
# or /foo,/foo/index.html
curl localhost:8000/projects/foo/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<h1>foo</h1>
</body>
</html>