How to configure node-fetch to use the company proxy?
Asked Answered
M

2

13

I am executing a standalone nodejs script (no web server involved) that needs to fetch result from a third party api. The program uses 'node-fetch' to do the fetch(url) and I run it using node .\test.js from command line.

It fails when I am connected to our company network but works fine on direct internet. I have configured the proxy settings in npm and could see that npm config ls shows the correct values for proxy and https-proxy.

So the questions are: 1. Does running the test.js via node not pick the proxy config from npm? 2. How to make sure that the fetch(url) call goes through our proxy?

Thanks in advance

Marinate answered 11/2, 2020 at 5:23 Comment(0)
T
18

This worked for me, try using this : https://github.com/TooTallNate/proxy-agents

The request formed will be similar to this:

fetch('accessUrl', {agent: new HttpsProxyAgent('proxyHost:proxyPort')})
    .then(function (res) {
    })
Trajectory answered 11/2, 2020 at 5:57 Comment(2)
and what if authentication?Realty
@PeterPalmer for me this works if you need authetication username:[email protected]:8080; this format is normally used even when doing it from curl for exampleDeneb
C
0

https://github.com/gajus/global-agent offers a neat way to use a proxy without modifying the code, so production will be untouched.

npm i global-agent --save-dev

Pass GLOBAL_AGENT_HTTPS_PROXY, GLOBAL_AGENT_HTTP_PROXY and -r global-agent/bootstrap to your local/test Node process:

"scripts": {
    "main": "node ./main.js",
    "test": "GLOBAL_AGENT_HTTPS_PROXY=http://127.0.0.1:1234 GLOBAL_AGENT_HTTP_PROXY=http://127.0.0.1:1234 node -r global-agent/bootstrap ./test.js"
}

You may also want to set GLOBAL_AGENT_NO_PROXY for requests that don't need the proxy.

Colmar answered 10/7, 2024 at 11:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.