javascript - Node.js 中的拦截器

标签 javascript node.js interceptor koa

我尝试过在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/

相关文章:

Javascript - 清空对象而不是创建新对象

javascript - 为什么反向 animate() 没有立即触发?

javascript - Node js : receive data from client

java - 允许 Spring 在不同的 jars 中有多个 WebMvcConfigurer 实现

java - Struts2中如何在加载页面之前执行一个 Action ?

hadoop - Flume 架构 : Events passing to Channel

javascript - 选择数组内部的所有数组元素

node.js - 在 Node.js 中导入 React 会抛出 SyntaxError : Unexpected token export

javascript - 找不到 babel 运行时库

带分页的 php 搜索表单