Categories
JavaScript Answers

How to create a simple http proxy in Node.js?

Spread the love

To create a simple http proxy in Node.js, we use the http-proxy package.

For instance, we write

const http = require("http");
const httpProxy = require("http-proxy");
const proxy = httpProxy.createProxyServer({});

http
  .createServer((req, res) => {
    proxy.web(req, res, { target: "http://www.example.com" });
  })
  .listen(3000);

to call http.createServer to create a web server.

We call it with a callback that calls proxy.web to create a proxy that redirects requests to http://www.example.com

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 *