2017-08-28 86 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之前。否則,請求將不會被傳送。

相關問題