简体   繁体   English

npm请求包的拦截器

[英]Interceptor for npm request package

I am working on an Express JS web application. 我正在开发Express JS Web应用程序。 I have 3 layers in my application. 我的应用程序中有3层。 External API server, Express and Angular as front end. 外部API服务器,Express和Angular作为前端。 So each AJAX requests from front end should pass through express in order to reach the API server and the same way, response too. 因此来自前端的每个AJAX请求也应以相同的方式通过快递到达API服务器,响应。 Authentication is managed by API server. 身份验证由API服务器管理。 When I send request to login from Angular, it will reach Express first, then Express will sent a request to API server, API server will send the Authentication token to Express and Express will pass it to the front end. 当我从Angular发送登录请求时,它将首先到达Express,然后Express将向API服务器发送请求,API服务器将向Express发送身份验证令牌,而Express会将其传递给前端。 So all the request from Angular will send the Authentication token as header to Express, express will send the corresponding request with the access token. 因此,来自Angular的所有请求都会将身份验证令牌作为标头发送到Express,express将发送带有访问令牌的相应请求。 This how my application works. 这就是我的应用程序的工作方式。 I know little complicated. 我知道有点复杂。 Now I am retrieving the access token from front end request and pass it to the API server in all the Controllers. 现在,我从前端请求中检索访问令牌,并将其传递给所有Controller中的API服务器。 What I want to do is, I have to write an interceptor which will globally retrieve the access token from the front end request and will pass to the API server. 我想做的是,我必须编写一个拦截器,该拦截器将从前端请求中全局检索访问令牌并将其传递给API服务器。

You can add an application middleware in your main file ie (app.js/server.js) above your routes. 您可以在路径上方的主文件(app.js/server.js)(app.js/server.js)添加application middleware

function interceptor(req, res, next) {
  let headers = req.headers;
  headers.someHeader = 'xyz'; // add your headers like this 
  request('your server url here', {
    method: req.method,
    headers: headers,
  }, (err, response, body) => {
    if (err) {
      next(err);
    }
    else {
      console.log(response.request.headers);
      res.send('OK');
    }
  });
}
app.use(interceptor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM