Node-http-proxy: Changing the response status code

Created on 16 Nov 2016  路  2Comments  路  Source: http-party/node-http-proxy

I need to change the status code on some responses before passing them on based on the data in them. Their body is a JSON object containing a field that determines this. I have only found a way (using middleware) to change the body content:

const app = express()
.use(function (req, res, next) {
    var _write = res.write;

    res.write = function (data) {
      _write.call(res, (data) => {/*some function that returns modified data*/});
    }
    next();
  }

However I found no way to change the status code and status message. Doing this:
res.statusCode = 400
has no effect on the response my client receives.

Most helpful comment

I was able to do this by overriding the writeHead function

// Avoid setting cookie from core (stateless behaviour)
coreProxy.on('proxyRes', (proxyRes, req, res) => {
  const originalWriteHead = res.writeHead;
  const originalWrite = res.write;
  const originalEnd = res.end;

  let jsonString = '';

  Object.assign(res, {
    writeHead: () => {},
    write: (chunk) => {
      jsonString += chunk.toString();
    },
    end: () => {
      // remove set-cookie header
      const headers = Object
        .keys(proxyRes.headers)
        .reduce((acc, key) => {
          const value = key === 'set-cookie' ? [] : proxyRes.headers[key];
          return Object.assign({}, acc, { [key]: value });
        }, {});

      const originalJSONResponse = JSON.parse(jsonString);

      // determine the status code base on error class name
      let statusCode = 200;
      if (originalJSONResponse.error) {
        const { errorClassName } = originalJSONResponse;
        switch (errorClassName) {
          case 'NeedsToBeDisplayedToUserException':
            statusCode = 400;
            break;
          case 'NotFoundException':
            statusCode = 404;
            break;
          default:
            statusCode = 500;
        }
      }

      originalWriteHead.apply(res, [statusCode, headers]);
      originalWrite.call(res, new Buffer(JSON.stringify(originalJSONResponse)));
      originalEnd.call(res);
    },
  });
});

// Proxy requests with url patten (*/core/*) to core (in a stateless fashion)
app.use((req, res, next) => {
  if (req.originalUrl.indexOf('/core/') !== -1) {
    coreProxy.web(req, res);
  } else {
    next();
  }
});

All 2 comments

+1

I was able to do this by overriding the writeHead function

// Avoid setting cookie from core (stateless behaviour)
coreProxy.on('proxyRes', (proxyRes, req, res) => {
  const originalWriteHead = res.writeHead;
  const originalWrite = res.write;
  const originalEnd = res.end;

  let jsonString = '';

  Object.assign(res, {
    writeHead: () => {},
    write: (chunk) => {
      jsonString += chunk.toString();
    },
    end: () => {
      // remove set-cookie header
      const headers = Object
        .keys(proxyRes.headers)
        .reduce((acc, key) => {
          const value = key === 'set-cookie' ? [] : proxyRes.headers[key];
          return Object.assign({}, acc, { [key]: value });
        }, {});

      const originalJSONResponse = JSON.parse(jsonString);

      // determine the status code base on error class name
      let statusCode = 200;
      if (originalJSONResponse.error) {
        const { errorClassName } = originalJSONResponse;
        switch (errorClassName) {
          case 'NeedsToBeDisplayedToUserException':
            statusCode = 400;
            break;
          case 'NotFoundException':
            statusCode = 404;
            break;
          default:
            statusCode = 500;
        }
      }

      originalWriteHead.apply(res, [statusCode, headers]);
      originalWrite.call(res, new Buffer(JSON.stringify(originalJSONResponse)));
      originalEnd.call(res);
    },
  });
});

// Proxy requests with url patten (*/core/*) to core (in a stateless fashion)
app.use((req, res, next) => {
  if (req.originalUrl.indexOf('/core/') !== -1) {
    coreProxy.web(req, res);
  } else {
    next();
  }
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

WHK102 picture WHK102  路  5Comments

mbret picture mbret  路  5Comments

miton18 picture miton18  路  5Comments

catamphetamine picture catamphetamine  路  6Comments

jsmylnycky picture jsmylnycky  路  3Comments