【问题标题】:How to handle the static folder in deno如何处理 deno 中的静态文件夹
【发布时间】:2021-07-10 18:06:37
【问题描述】:

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

这是在 deno 中使用 Oak 库处理静态文件的方法:

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');
}

感谢您的帮助。

【问题讨论】:

    标签: typescript static-files deno


    【解决方案1】:

    这能回答你的问题吗?

    示例:动态检查现有文件夹,如果没有找到会报错: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>
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多