【问题标题】:Fastify-http-proxy unable to get dynamic routesFastify-http-proxy 无法获取动态路由
【发布时间】:2021-11-18 20:42:55
【问题描述】:

我有一个指向两个“后端”的 fastify 服务器,我想生成一个随机数,然后用来决定路由到哪个后端。

目前它只在第一次工作,之后我无法覆盖上游。

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})

我怎样才能让它在刷新时改变它的路由?

【问题讨论】:

  • 每次刷新都看到console.log()语句了吗?你是说它击中了“其他”条件分支但没有更新路径?
  • 是的,我每次刷新都会看到它。它看起来像这样:将 base 设置为 backend2 打 backend2 将 base 设置为 backend1 打 backend2
  • 然后你在运行时就看不到任何console.log语句了?
  • 对不起,我应该指定我要去 localhost:3000 并在那里刷新(不是重新运行节点 server.js),所以每次刷新网页时我都会看到 console.log 语句运行节点。做卷曲时我得到了同样的效果

标签: javascript fastify


【解决方案1】:

想通了。 disableCache 需要在 replyOptions 之外。

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2016-06-12
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多