【问题标题】:Dynamically created proxy URL using Node/Express使用 Node/Express 动态创建的代理 URL
【发布时间】:2017-03-12 17:18:59
【问题描述】:

我想使用 express 来使用我存储在数据库中的 URL 创建唯一代理实例。我发现了一个名为 http-express-proxy 的 npm 模块可能对此有所帮助,但对使用 express 的其他解决方案开放。

我有一个这样的路由(使用 http-express-proxy):

user.URL = 'https://www.google.com'

app.post('/', proxy(user.URL))

// and after this, user.URL is updated to a different value. I want the proxy's address to change too.

我确实找到了在运行时动态创建常规快速路由的解决方案,但我无法使用 http-express-proxy 中的 proxy() 方法使其工作:

https://alexanderzeitler.com/articles/expressjs-dynamic-runtime-routing/

根据这种方法,我可以在 POST 路由中要求第二个文件,如下所示:(并包括使用 sequelize 对数据库的调用)

const express = require('express')
const proxy = require('express-http-proxy')

const User = require('../db/models/user')

const app = express()

module.exports= {
    init : init
}
function init(app) {
    User.findOne({where: {id: 1}})
        .then(user => app.post('/', proxy(user.URL)))   
}

然后在我的主 app.js 文件中,我正在这样做:

// ...

app.post('/', function(req, res, next) { 
    var dynamic = require('./dynamic')
    dynamic.init(app)
})

// ...

但是,当我使用 http-express-proxy 发布此方法时,我收到了 503 响应,他的示例中没有使用该方法。

【问题讨论】:

  • 这听起来可能很荒谬,但这不是因为您的数据示例有小写的url 并且代码有user.URL?如果你 console.log 它,user.URL 会出现什么结果,proxy(user.URL) 函数的结果也是如此?
  • 是的@MattFletcher,我的数据结构不一致。这不是实际的代码,而是作为示例。我现在会更新这个。

标签: node.js express proxy


【解决方案1】:

我让它像这样工作。我修改了 express-http-proxy 模块,并在 SendProxyRequest() 方法的顶部添加了这个:

if (req.URL) host = req.URL

然后在我的 app.js 文件中,我添加了一个中间件方法来在调用数据库后设置 req.URL:

function getProxyURL (req, res, next) {
    User.findOne({where: {id: 1}})
        .then(user => {
            if(user.URL) req.URL = user.URL
            next()
        })
}

app.post('/', getProxyURL, proxy('www.default.com'))

【讨论】:

  • 要将此标记为您的首选答案,请在系统允许时单击旁边的勾号。谢谢。
  • 这个答案不再起作用,产生TypeError: Cannot read property 'URL' of undefined
猜你喜欢
  • 2014-04-14
  • 2014-11-25
  • 2014-03-18
  • 2015-06-20
  • 2017-10-06
  • 1970-01-01
  • 2013-03-21
  • 2022-01-07
  • 2021-02-25
相关资源
最近更新 更多