Implementation of api Gateway Using express http proxy in Node

  • 2021-08-28 19:29:04
  • OfStack

Copy the code memo, filter filter the request, proxyReqOptDecorator rewrite the request header, the code is as follows:


var express = require('express');
var proxy = require('express-http-proxy')

var app = express();

app.all('*', function (req, res, next) {
 res.header("Access-Control-Allow-Origin", req.headers.origin);
 res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
 res.header("Access-Control-Allow-Credentials", "true");
 res.header("Content-Type", "application/json;charset=utf-8");
 if (req.method == 'OPTIONS') {
  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
  res.send(200); /* Jean options Request a quick return */
 }
 else {
  next();
 }
});

//  Code forwarding 
app.use('/ProxySSO', proxy(req => {
 return req.headers.apiurl
}, {
 filter: function (req, res) {

  //  User name \ System identification \ User rights 
  let { systemName, masterName, powers } = req.tokenDecode;
  const { originalUrl } = req;
  const url = originalUrl.replace('/ProxySSO', '').split('?')[0];

  /**
   *  Interface permission check 
   * @param {String} url  Interface address 
   * @param {Object} powers rbac Permission list 
   * @returns {boolean}  Do you have permission 
   */
  const checkPowers = (url, powers) => {
    //  do something
  }
  const hasPowers = checkPowers(url, powers);
   //  Authority judgment 
  return hasPowers;
 },
 proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
  // header Increase masterName  According to your own needs 
  // proxyReqOpts.headers['masterName'] = srcReq.tokenDecode.masterName;
  return proxyReqOpts;
 }
}));

module.exports = app;


Related articles: