Home > Web Front-end > JS Tutorial > How to use a proxy in a nodejs environment

How to use a proxy in a nodejs environment

Susan Sarandon
Release: 2024-12-14 10:01:10
Original
658 people have browsed it

How to use a proxy in a nodejs environment

There is an established standard by which proxies are configured. It runs via the following environment variables:

  • https_proxy: Proxy for https traffic
  • http_proxy: Proxy for http traffic
  • no_proxy: URLs that should not run via a proxy.

The native fetch client of NodeJS does not offer any functionality for this out-of-the-box, but there is an agent from the undici http client that you can use:

import { EnvHttpProxyAgent } from "undici";

const ENV_HTTP_PROXY_AGENT = new EnvHttpProxyAgent();
const proxyAgent = { dispatcher: ENV_HTTP_PROXY_AGENT } as any;

await fetch("https://...", {
  ...proxyAgent,
});
Copy after login

The node type definition does not support a dispatcher attribute for fetch, but it's a supported logic. So if you're using TypeScript you can ignore the error or use the beloved as any pattern for the proxy agent.

And that's everything, no manual evaluation of the environment variables. Everything is handled by the EnvHttpProxyAgent from undici.

The above is the detailed content of How to use a proxy in a nodejs environment. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template