在本教程中,我们展示了如何在 JavaScript 中创建和使用代理。
代理 服务器是一种服务器应用程序,充当请求资源的客户端和提供该资源的服务器之间的中介。
出于各种原因使用代理,包括授权、匿名化、负载平衡和日志记录。
JS代理示例
在我们的示例中,我们使用 Express 框架和 http-proxy 模块。我们将向 webcode.me 网站发送一个简单的 HTTP GET 请求,该网站将通过本地基于 Express 的 Web 应用程序进行代理。
$ npm install express http-proxy
我们安装这两个模块。
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'));
这是一个简单的 Express 应用程序,它记录请求并将其发送到最终目标。
app.get('*', (req, res) => {
console.log('Request', req.method, req.url);
proxy.web(req, res, { target: `${req.protocol}://${req.hostname}` });
});
所有请求都被转发到最终目的地。我们将请求详细信息记录到控制台。
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();
使用 Axios,我们创建一个 GET 请求到http://webcode.mewebpage。它通过侦听localhost:3000 的代理发送。
$ node server.js Application started on port 3000
我们启动服务器应用程序。
$ 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>
我们创建一个 GET 请求并接收响应。服务器将Request GET http://webcode.me/ 消息记录到控制台。
在本文中,我们使用了 JavaScript 中的代理。
列出所有 JavaScript 教程。
