Categories
JavaScript Answers

How to create a proxy with Express.js?

Spread the love

Sometimes, we want to create a proxy with Express.js.

In this article, we’ll look at how to create a proxy with Express.js.

How to create a proxy with Express.js?

To create a proxy with Express.js, we can use the express-http-proxy package.

To install it, we run

npm i express-http-proxy

Then we write

const url = require('url');
const proxy = require('express-http-proxy');

const apiProxy = proxy('example.com:3000/test', {
  proxyReqPathResolver: req => url.parse(req.baseUrl).path
});

to call proxy with the URL we want to proxy and an object that has the proxyReqPathResolver property set to a function to map the URL we’re proxy to a URL in our app.

url.parse parses the URL and we get the URL path with path.

Conclusion

To create a proxy with Express.js, we can use the express-http-proxy package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *