沒有標準方式可針對Node.js應用程式啟用 Proxy。 您是否可以使用 Proxy,取決於您用來提出 HTTP 要求的連結庫。 一般而言,您需要更新程式代碼來設定 Proxy。 不過, global-agent
您可以使用套件,以最少的程式代碼變更,為Node.js應用程式啟用 Proxy 支援。
原生Node.js擷取 API
在 v17.5.0 中,Node.js 引進了對 fetch
API 的實驗性支援。 不幸的是,此 API 仍然有限,且不支持設定 Proxy。 如果您想要將 Dev Proxy 搭配 Node.js 使用,您必須使用不同的函式庫來提出 HTTP 要求。
global-agent
global-agent
是一個熱門的函式庫,可為 Node.js 提供全域性的 HTTP/HTTPS 協定代理程式。 它可讓您使用環境變數來指定 Proxy。 使用 global-agent
的優點是,您不需要變更在應用程式中發出 HTTP 要求以使用 Dev Proxy 的方式。
以下是如何在使用 node-fetch
的 Node.js 應用程式中使用 global-agent
的範例:
import fetch from 'node-fetch';
import { bootstrap } from 'global-agent';
bootstrap();
(async () => {
const result = await fetch('https://jsonplaceholder.typicode.com/posts');
const jsonResult = await result.json();
console.log(JSON.stringify(jsonResult, null, 2));
})();
以下是您可以搭配Node.js和標準global-agent
模組使用https
的方式:
const https = require('https');
const globalAgent = require('global-agent');
globalAgent.bootstrap();
https.get('https://jsonplaceholder.typicode.com/posts', (resp) => {
let data = '';
resp.on('data', (d) => {
data += d;
});
resp.on('end', () => {
console.log(JSON.parse(data));
});
resp.on('error', (err) => {
console.error(err);
});
});
啟動應用程式時,請使用 GLOBAL_AGENT_HTTP_PROXY
環境變數指定 Proxy,並忽略憑證錯誤。
NODE_TLS_REJECT_UNAUTHORIZED=0 GLOBAL_AGENT_HTTP_PROXY=http://127.0.0.1:8000 node global-node-fetch.mjs
node-fetch
node-fetch 是廣受歡迎的函式庫,提供用於 Node.js 的 fetch
實作。
node-fetch
不支援使用環境變數指定 Proxy。 相反地,您必須建立自定義代理程式,並將其傳遞至 fetch
方法。
以下範例說明如何使用 node-fetch
套件來定義代理程式,以搭配開發 Proxy 使用 https-proxy-agent
。
const fetch = require('node-fetch');
const { HttpsProxyAgent } = require('https-proxy-agent');
(async () => {
// Create a custom agent pointing to Dev Proxy
const agent = new HttpsProxyAgent('http://127.0.0.1:8000');
// Pass the agent to the fetch method
const result = await fetch('https://jsonplaceholder.typicode.com/posts', { agent });
const jsonResult = await result.json();
console.log(JSON.stringify(jsonResult, null, 2));
})();
Axios
Axios 是另一個熱門連結庫,用於在 Node.js 中提出 HTTP 要求。 Axios 可讓您使用環境變數指定 Proxy,或直接在要求組態中指定代理程式。
搭配環境變數使用 Axios 和 Dev Proxy
當您搭配 Axios 使用 Dev Proxy 並使用環境變數指定 Proxy 時,您不需要變更程式碼。 您只需要設定環境變數, https_proxy
而 Axios 會用它來提出要求。
import axios from 'axios';
(async () => {
const result = await axios.get('https://jsonplaceholder.typicode.com/posts');
const response = result.data;
console.log(JSON.stringify(response, null, 2));
})();
請在全域或啟動應用程式時指定https_proxy
環境變數。
https_proxy=http://127.0.0.1:8000 node axios.mjs
了解
類似於 node-fetch
, Got 不支援使用環境變數指定 Proxy。 相反地,您必須建立自定義代理程式,並將其傳遞至要求。
以下是如何使用 Got 程式庫與 Dev Proxy 進行搭配的範例:
import got from 'got';
import { HttpsProxyAgent } from 'https-proxy-agent';
(async () => {
// Create a custom agent pointing to Dev Proxy
const agent = new HttpsProxyAgent('http://127.0.0.1:8000');
const result = await got('https://jsonplaceholder.typicode.com/posts', {
// Pass the agent to the fetch method
agent: {
https: agent
},
// Disable certificate validation
https: {
rejectUnauthorized: false
}
}).json();
console.log(JSON.stringify(result, null, 2));
})();
SuperAgent
SuperAgent
不支援使用環境變數指定 Proxy。 若要搭配 SuperAgent 使用 Dev Proxy,您必須安裝 superagent-proxy
外掛程式,並使用 proxy
方法來設定 Proxy。
const superagent = require('superagent');
require('superagent-proxy')(superagent);
(async () => {
const result = await superagent
.get('https://jsonplaceholder.typicode.com/posts')
.proxy('http://127.0.0.1:8000')
// Disable certificate validation
.disableTLSCerts();
console.log(JSON.stringify(result.body, null, 2));
})();
已知問題
當您搭配Node.js使用Dev Proxy時,可能會遇到下列問題。
UNABLE_TO_VERIFY_LEAF_SIGNATURE
錯誤
當您搭配Node.js使用 Dev Proxy 時,會收到類似下列的錯誤:
/Users/user/my-app/node_modules/node-fetch/lib/index.js:1501
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
^
FetchError: request to https://jsonplaceholder.typicode.com/posts failed, reason: unable to verify the first certificate
at ClientRequest.<anonymous> (/Users/user/my-app/node_modules/node-fetch/lib/index.js:1501:11)
at ClientRequest.emit (node:events:518:28)
at TLSSocket.socketErrorListener (node:_http_client:495:9)
at TLSSocket.emit (node:events:518:28)
at emitErrorNT (node:internal/streams/destroy:169:8)
at emitErrorCloseNT (node:internal/streams/destroy:128:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
type: 'system',
errno: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}
若要修正此問題,您必須將 NODE_TLS_REJECT_UNAUTHORIZED
環境變數設定為 0
。 您可以在全域定義它,或在啟動應用程式時內嵌定義它。
NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js