繁体   English   中英

我如何使用 fastify/static 和基于 header 的自定义路由来提供相同的路由?

[英]How can I serve the same route with fastify/static and a custom route based on header?

举例来说,我有一条路线/object/:id ,我想默认使用 fastify/static 服务STATIC_FOLDER/object/<supplied id>/index.html 这真的很简单,我只是用STATIC_FOLDER作为根注册 fastify/static。

我也想要相同的路由(即/object/:id ),如果“Content-Type”header 设置为“application/json”,使用自定义逻辑检索相关数据并返回 json。这很简单足以实现。

但是我如何同时实现两者呢?

如果我设置 fastify/static,那么 static 文件就可以正常运行了。 如果我还像这样设置自定义路由:

fastify.get('/object/:id', async function (request, reply) {
  // ... custom logic to get obj by id
  reply.type('application/json').code(200).send(obj)
}

然后它只调用该路由并返回 json。

有什么办法可以根据 Content-Type header 在路线上添加过滤器或其他东西吗?
我试着查看路线选项文档,但找不到任何相关内容。

使用 Fastify,你可以做任何事情

您需要配置路由约束

它们一点也不冗长,所以在这个例子中我使用了header-constraint-strategy插件,它简化了很多实现

const path = require('path');
const Fastify = require('fastify')
const fastifyStatic = require('@fastify/static')
const headerConstraintStrategy = require('header-constraint-strategy')

const app = Fastify({
  logger: true,
  constraints: {
    ct: headerConstraintStrategy({ name:'ct', header: 'content-type' }),
  }
})

app.register(fastifyStatic, {
  root: path.join(__dirname, 'public'),
})

app.get('/object/:id', {
  handler: (request) => {
    return { hello: request.params.id }
  },
  constraints: {
    ct: 'application/json'
  }
})

app.listen({port:8080})

// curl http://localhost:8080/object/my-id -H 'content-type:application/json'
// print: {"hello":"my-id"}%
                                                                                                                                                                   
// curl http://localhost:8080/object/my-id                                   
// print: hello%

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM