我尝试过在node js中构建一个拦截器,但到目前为止我还没有得到它。我想要拦截器来捕获每个请求并添加一个自定义 header ,从 koa 上下文中恢复。
我的意思是,例如,如果您使用 request-promise 进行 http 请求,我想自动添加自定义 header 并将其传播到命运。
有人知道吗?
最佳答案
拦截器基本上是中间件。
// before all
app.use(function *(next) {
this.set('x-new-header', 'value');
yield next;
});
// the rest
app.use(routes());
如果您的 Koa 应用程序充当反向代理。您可以使用 pipe
API 将新 header 传播到远程服务器。
// 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));
});
关于javascript - Node.js 中的拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941586/