使用Node / Express动态创建代理URL

时间:2017-03-12 17:18:59

标签: node.js express proxy

我想使用express来创建使用我存储在数据库中的URL的唯一代理实例。我找到了一个npm模块可以帮助这个名为 http-express-proxy 但可以使用 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响应,这在他的示例中没有使用。

1 个答案:

答案 0 :(得分:0)

我让它像这样工作。我修改了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'))