2017-08-28 87 views
1

我们使用的一个SaaS提供商有一个webook字段,但只允许输入一个url。实际上,我们需要将此webhook发送给两个分析服务,因此我需要找出一种方法来编写自定义端点,以将整个请求转发到我们需要的其他端点(当前为2个)。如何将一个POST请求转发到两个外部URL?

用node和express做这个最简单的方法是什么?如果我没有弄错,简单的重定向不适用于多个POST,对吧?

我不知道什么头,甚至要求内容将是什么样子,但它需要在身份验证的情况下被保留尽可能在头等等

这是我到目前为止,但它远不完整:

app.post('/', (req, res) => { 
console.log('Request received: ', req.originalUrl) 
const forwardRequests = config.forwardTo.map(url => { 
    return new Promise((resolve, reject) => { 
    superagent 
     .post(url) 
     .send(req) 
     .end((endpointError, endpointResponse) => { 
     if (endpointError) { 
      console.error(`Received error from forwardTo endpoint (${url}): `, endpointError) 
      reject(endpointError) 
     } else { 
      resolve(endpointResponse) 
     } 
     }) 
    }) 
}) 
Promise.all(forwardRequests) 
    .then(() => res.sendStatus(200)) 
    .catch(() => res.sendStatus(500)) 
}) 

我得到一个错误,因为superagent.send仅仅是内容...我怎么能完全复制的请求,并把它关闭

回答

1

完全复制的请求,并把它送上各种端点,可以使用request模块req.pipe(request(<url>))Promise.all

根据请求模块的文件:

您还可以通过管道()从http.ServerRequest情况,以及对http.ServerResponse实例。 HTTP方法,头文件和实体主体数据将被发送。

下面是一个例子:

const { Writable } = require('stream'); 
const forwardToURLs = ['http://...','http://...']; 
app.post('/test', function(req, res) { 
    let forwardPromiseArray = []; 
    for (let url of forwardToURLs) { 
    let data = ''; 
    let stream = new Writable({ 
     write: function(chunk, encoding, next) { 
     data += chunk; 
     next(); 
     } 
    }); 
    let promise = new Promise(function(resolve, reject) { 
     stream.on('finish', function() { 
     resolve(data); 
     }); 
     stream.on('error', function(e) { 
     reject(e); 
     }); 
    }); 
    forwardPromiseArray.push(promise); 
    req.pipe(request(url)).pipe(stream); 
    } 

    Promise.all(forwardPromiseArray).then(function(result) { 
    // result from various endpoint, you can process it and return a user-friendly result. 
    res.json(result); 
    }).catch(function() { 
    res.sendStatus(500); 
    }); 
}); 

请注意上面的代码应该(如果你使用的话)置于body-parser之前。否则,请求将不会被传送。

相关问题