Usare Dev Proxy con applicazioni Node.js
Non esiste un modo standard per abilitare i proxy per le applicazioni Node.js. Indipendentemente dal fatto che sia possibile usare il proxy, dipende dalla libreria usata per effettuare richieste HTTP. In genere, è necessario aggiornare il codice per configurare il proxy. È tuttavia possibile usare il pacchetto per abilitare il global-agent
supporto proxy per l'applicazione Node.js con modifiche minime al codice.
API di recupero Node.js nativa
Nella versione 17.5.0 Node.js introduce il supporto sperimentale per l'API fetch
. Sfortunatamente, questa API è ancora limitata e non supporta la configurazione di un proxy. Se si vuole usare Dev Proxy con Node.js, è necessario usare una libreria diversa per effettuare richieste HTTP.
global-agent
global-agent
è una libreria comune che fornisce un agente HTTP/HTTPS globale per Node.js. Consente di specificare il proxy usando le variabili di ambiente. Il vantaggio dell'uso global-agent
è che non è necessario modificare il modo in cui si emettono richieste HTTP nell'applicazione per usare Dev Proxy.
Ecco un esempio di come è possibile usare global-agent
in un'applicazione Node.js che usa node-fetch
:
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));
})();
Ecco come usare global-agent
con Node.js e il modulo standard 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);
});
});
Quando si avvia l'applicazione, specificare il proxy usando la GLOBAL_AGENT_HTTP_PROXY
variabile di ambiente e ignorare gli errori del certificato.
NODE_TLS_REJECT_UNAUTHORIZED=0 GLOBAL_AGENT_HTTP_PROXY=http://127.0.0.1:8000 node global-node-fetch.mjs
node-fetch
node-fetch è una libreria comune che fornisce un'implementazione fetch
per Node.js. node-fetch
non supporta la specifica del proxy usando le variabili di ambiente. È invece necessario creare un agente personalizzato e passarlo al fetch
metodo .
Ecco un esempio di come usare node-fetch
con Dev Proxy definendo un agente usando il https-proxy-agent
pacchetto.
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 è un'altra libreria popolare per l'esecuzione di richieste HTTP in Node.js. Axios consente di specificare il proxy usando variabili di ambiente o specificare l'agente direttamente nella configurazione della richiesta.
Usare Axios e Dev Proxy con variabili di ambiente
Quando si usa Dev Proxy con Axios e si specifica il proxy usando le variabili di ambiente, non è necessario modificare il codice. È sufficiente impostare la https_proxy
variabile di ambiente e Axios lo usa per effettuare richieste.
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));
})();
Specificare la https_proxy
variabile di ambiente a livello globale o all'avvio dell'app.
https_proxy=http://127.0.0.1:8000 node axios.mjs
Ottenuto
Analogamente a node-fetch
, Got non supporta la specifica del proxy usando le variabili di ambiente. È invece necessario creare un agente personalizzato e passarlo alla richiesta.
Ecco un esempio di come usare Got with 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
non supporta la specifica del proxy usando le variabili di ambiente. Per usare Dev Proxy con SuperAgent, è necessario installare il superagent-proxy
plug-in e configurare il proxy usando il proxy
metodo .
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));
})();
Problemi noti
Quando si usa Dev Proxy con Node.js, è possibile che si verifichino i problemi seguenti.
UNABLE_TO_VERIFY_LEAF_SIGNATURE
errori
Quando si usa Dev Proxy con Node.js, viene visualizzato un errore simile al seguente:
/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'
}
Per risolvere questo problema, è necessario impostare la NODE_TLS_REJECT_UNAUTHORIZED
variabile di ambiente su 0
. È possibile definirlo a livello globale o in linea all'avvio dell'app.
NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js