how to run node js with proxy
- Install the 'http-proxy' module using npm:
bash
npm install http-proxy
- Create a new Node.js file (e.g.,
app.js
) and require the necessary modules:
javascript
const http = require('http');
const httpProxy = require('http-proxy');
- Create an instance of the proxy and specify the target server:
javascript
const targetServer = 'http://your-target-server.com';
const proxy = httpProxy.createProxyServer({ target: targetServer });
- Handle proxy server errors:
javascript
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Proxy server error.');
});
- Create a new HTTP server and handle incoming requests:
javascript
const server = http.createServer(function (req, res) {
// You can add custom logic here if needed before proxying the request
proxy.web(req, res);
});
- Specify the port for your proxy server to listen on:
javascript
const port = 3000;
server.listen(port);
- Start the proxy server and print a message once it's running:
javascript
server.on('listening', function () {
console.log(`Proxy server listening on port ${port}`);
});
Optionally, you can add additional logic before or after proxying requests by modifying the request or response objects.
Save the file and run your Node.js application:
bash
node app.js
This will start your Node.js server with a proxy that forwards requests to the specified target server. Adjust the target server URL and port as needed.