微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何处理 deno 中的静态文件夹

如何解决如何处理 deno 中的静态文件夹

我想知道是否可以根据 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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。