GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — JavaScript Proxy - Intercepting Object Operations JavaScript proxylast modified last modified October 18, 2023 In this tutorial, we show how to create and use a proxy in JavaScript. A proxy server is a server application that acts as an intermediary between a client requesting a resource and the server providing that resource. Proxies are used for various reasons, including authorization, anonymization, load balancing and logging. JS proxy exampleIn our example, we use Express framework and http-proxy module. We are going to send a simple HTTP GET request to webcode.me website, which is going to be proxied over a local Express-based web application. $ npm install express http-proxy We install the two modules. server.js
const express = require('express');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const app = express();
app.get('*', (req, res) => {
console.log('Request', req.method, req.url);
proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});
app.listen(3000, () => console.log('Application started on port 3000'));
This is a simple Express applications which logs the request and sends it to the final target. app.get('*', (req, res) => {
console.log('Request', req.method, req.url);
proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});
All requests are forwarded to the final destination. We log the request details to the console. client.js
const axios = require('axios');
async function doGetRequest() {
const res = await axios.get('http://webcode.me', {
proxy: {
host: 'localhost',
port: 3000
}
});
console.log(res.data);
}
doGetRequest();
With Axios, we create a GET request to the $ node server.js Application started on port 3000 We start the server application. $ node main.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="format.css">
<title>My html page</title>
</head>
<body>
<p>
Today is a beautiful day. We go swimming and fishing.
</p>
<p>
Hello there. How are you?
</p>
</body>
</html>
We create a GET request and receive a response. The server logs the
SourceIn this article we have worked with a proxy in JavaScript. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |