【问题标题】:How Can I Serve Static Content Alongside Dynamic Routes in A Deno Oak Server如何在 Deno Oak 服务器中与动态路由一起提供静态内容
【发布时间】:2020-12-28 15:32:19
【问题描述】:

我习惯于使用 NodeJS 和 Koa。我一直在玩 Deno 并运行了静态文件服务器的示例:


/* static_server.js */

import { Application } from 'https://deno.land/x/oak/mod.ts'

const port  = 8080

const app = new Application()

// Error handler middleware
app.use(async (context, next) => {
  try {
    await next()
  } catch (err) {
        console.error(err)
    }
})

// Send static content
app.use(async (context) => {
    console.log(`${context.request.method} ${context.request.url.pathname}`)
  await context.send({
    root: `${Deno.cwd()}/static`,
    index: "index.html",
  })
})


await app.listen({ port })

我还使用路由创建了一个动态服务器:


/* routes.js */

import { Application, Router } from 'https://deno.land/x/oak/mod.ts'

const port = 8080

const app = new Application()
const router = new Router()

router.get('/', context => {
    context.response.body = 'Hello world!'
  })

router.get('/foo', context => {
    context.response.body = 'Book Page'
  })

router.get('/foo/:thing', context => {
    context.response.body = `Foo ${context.params.thing}`
})

app.use(router.routes())
app.use(router.allowedMethods())

await app.listen({ port })

如何将这些结合起来,以便既可以提供动态内容,又可以提供样式表等静态文件?

在我的 Koa 代码中,我使用 koa-static 包:

import serve from 'koa-static'
app.use(serve('public'))

Oak 服务器的等价物是什么?

添加建议的代码(感谢 Jonas Wilms)


/* static_content.js */

import { Application, Router } from 'https://deno.land/x/oak/mod.ts'

const port = 8080

const app = new Application()
const router = new Router()

router.get('/', context => {
    context.response.body = 'Hello world!'
  })

router.get('/foo', context => {
    context.response.body = 'Book Page'
  })

router.get('/foo/:thing', context => {
    context.response.body = `Foo ${context.params.thing}`
})

router.get(context => context.send({ root: `${Deno.cwd()}/static` }))

app.use(router.routes())
app.use(router.allowedMethods())

await app.listen({ port })

但这仍然不起作用......

【问题讨论】:

  • router.all(context => context.send({ root: .. })); 应该可以工作(作为最后一条路线)。
  • 尝试添加此内容,但不起作用。我将尝试发布包含您建议的代码的当前版本。
  • “行不通”是什么意思?路线匹配吗?
  • 屏幕为空白,出现 404 错误。
  • 这可能会有所帮助:stackoverflow.com/questions/62443440/…

标签: javascript routes webserver deno oak


【解决方案1】:

在结合了 cmets 中的大量信息后,我设法让事情开始运作:


/* static_content.js */

import { Application, Router, Status } from 'https://deno.land/x/oak/mod.ts'

const port = 8080

const app = new Application()
const router = new Router()

// error handler
app.use(async (context, next) => {
  try {
    await next()
  } catch (err) {
        console.log(err)
  }
})

// the routes defined here
router.get('/', context => {
    context.response.body = 'Hello world!'
})

router.get('/error', context => {
    throw new Error('an error has been thrown')
})

app.use(router.routes())
app.use(router.allowedMethods())

// static content
app.use(async (context, next) => {
    const root = `${Deno.cwd()}/static`
    try {
        await context.send({ root })
    } catch {
        next()
    }
})

// page not found
app.use( async context => {
    context.response.status = Status.NotFound
  context.response.body = `"${context.request.url}" not found`
})

app.addEventListener("listen", ({ port }) => console.log(`listening on port: ${port}`) )

await app.listen({ port })


【讨论】:

    【解决方案2】:

    我知道我有点晚了,但我想指出一些事情。

    在 Oak 10.1(撰写本文时的当前版本)中,send 函数会在它厌倦加载的文件不存在时引发错误。因此,我们的静态+动态服务器可以采用以下形式。

    import { oak, pathUtils } from './deps.ts'
    
    const app = new oak.Application()
    const router = new oak.Router()
    
    app.use(async (ctx, next) => {
        try {
            await oak.send(ctx, ctx.request.url.pathname, {
                root: 'static',
                index: 'index.html',
            })
        } catch (_) {
            await next()
        }
    })
    
    router.get('/dynamic', ctx => {
        ctx.response.body = 'dynamic route worked'
    })
    
    app.use(router.allowedMethods())
    app.use(router.routes())
    
    app.listen({ port: 8000 })
    

    如果您想在某个根路径提供静态文件,请更改静态中间件,使其检查根,然后从 send 函数的第二个参数中省略该根路径。

    function staticMiddleware(rootPath: string, staticDirectory: string) {
        return async (ctx, next) => {
            if (!ctx.request.url.pathname.startsWith(rootPath)) return await next()
    
            const newPath = ctx.request.url.pathname.slice(rootPath.length)
            if (!newPath.startsWith('/') && newPath.length) return await next()
    
            try {
                await oak.send(ctx, newPath, {
                    root: staticDirectory,
                    index: 'index.html',
                })
            } catch (_) {
                await next()
            }
       }
    }
    
    app.use(staticMiddleware('/assets', 'static'))
    

    【讨论】:

      【解决方案3】:

      我认为你最后应该使用静态路由器。因为当先使用静态服务器时,动态路由器因静态路由器错误而无法访问。

      app.use(router.routes())
      app.use(router.allowedMethods())
      // move the static router down
      app.use( async context => {
        context.response.status = Status.NotFound
        context.response.body = `"${context.request.url}" not found`
      })
      

      【讨论】:

        【解决方案4】:

        我就是这样用的。在 html 中,您可以提供文件的路径:

        <script src="/js/app.js"></script>
        

        那么你可以使用路由来提供你想在路径 js/app.js 上使用什么:

        import {RouterContext} from 'https://deno.land/x/oak/mod.ts'
        
        const decoder = new TextDecoder("utf-8")// set doecoder
        const fileCont = await Deno.readFile('./views/test.js') //getting file conetent
        const fileJS = decoder.decode(fileCont) //decoding it
        
        router.get('/js/app.js', (ctx: RouterContext) => { //yep, route can has defferents of real file location
                ctx.response.type = "application/javascript"
                ctx.response.body = fileJS
            })
        

        无论您在某处提供此链接,它都会为您呈现文件。

        德诺REST API

        【讨论】:

          猜你喜欢
          • 2011-07-12
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 2020-03-04
          • 2013-04-03
          • 1970-01-01
          • 2020-07-07
          • 1970-01-01
          相关资源
          最近更新 更多