簡體   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