拦截器在Node.js中
我试图在节点js中构build一个拦截器,但到目前为止,我没有得到它。 我想拦截器,捕捉每个请求,并添加一个自定义标题,从koa上下文恢复。
我的意思是,例如,如果您使用request-promise进行http请求,我想自动添加一个自定义标题并将其传播到命运。
有人知道吗?
拦截器基本上是中间件。
// 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)); });