2017-01-30 43 views
2

我試圖在節點js中構建一個攔截器,但到目前爲止我沒有得到它。我想攔截器,捕捉每個請求並添加一個自定義頭,從koa上下文恢復。Node.js中的攔截器

我的意思是,例如,如果您使用request-promise進行http請求,我想自動添加一個自定義標題並將其傳播到命運。

有人知道嗎?

回答

1

攔截器基本上是中間件。

// before all 
app.use(function *(next) { 
    this.set('x-new-header', 'value'); 
    yield next; 
}); 

// the rest 
app.use(routes()); 

如果您的Koa應用程序的行爲像反向代理。您可以使用pipe API將新標頭傳播到遠程服務器。

// before all 
app.use(function *(next) { 
    this.set('x-new-header', 'value'); 
    yield next; 
}); 

// the reverse-proxy 
const request = require('co-request'); 
app.use(function *() { 
    this.body = this.req.pipe(request(config)); 
});