Sometimes, we want to create a simple HTTP proxy in Node.js.
In this article, we’ll look at how to create a simple HTTP proxy in Node.js.
How to create a simple HTTP proxy in Node.js?
To create a simple HTTP proxy in Node.js, we can use the http
and http-proxy
modules.
We install http-proxy
by running
npm install http-proxy --save
Then we use it by writing
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 create a proxy server with createProxyServer
.
Then we call http.createServer
with a callback to proxy our requests to http://www.example.com.
And we listen for requests on port 3000.
Conclusion
To create a simple HTTP proxy in Node.js, we can use the http
and http-proxy
modules.