How use proxyAgent only in development env

117 Views Asked by At

I´m currently forced to comment or uncomment a single line in my request object, depending if my application currently run my local system or the productive server.

I already tried to solve this problem with a bool variable, but it does not work. Here is my Code

const dev = true;
const devProxy = dev
  ? {agent: new HttpsProxyAgent("http://proxy:80")}
  : {};

 myFunc: async access_token => {
    const response = await fetch(
      URL,
      {
        // agent: new HttpsProxyAgent("http://proxy:89´0"),
        devProxy,
        method: "GET",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: `Bearer ${access_token.access_token}`
        }
      }
    );
    if (response.ok) {
      return response.json();
    }
    throw new Error(
      "bla" +
        response.status +
        " StatusText: " +
        response.statusText
    );
  },

The error says that the proxy was not used.

How can I correctly do it?

1

There are 1 best solutions below

0
On BEST ANSWER

Multiple things you can do, can isolate the object to another variable and set the agent. OR you can Object.assign the agent key as well. Simplest would be assigning a variable:

const dev = true;
const options = {
  method: "GET",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    Authorization: `Bearer ${access_token.access_token}`
  }
}
if (dev) options.agent = new HttpsProxyAgent("http://proxy:80");

myFunc: async access_token => {
  const response = await fetch(
    URL,
    options
  );
  if (response.ok) {
    return response.json();
  }
  throw new Error(
    "bla" +
    response.status +
    " StatusText: " +
    response.statusText
  );
},