Use proxy in nodejs to access external files

Asked

Viewed 452 times

0

I have a service on Nodejs that does a fetch to access an external api:

const express = require('express');
const middlewares = require('./middlewares/middlewares');
const routes = require('./routes');
const raven = require('raven');
const config = require('./config');
const mongoose = require('mongoose');
const winston = require('winston');
const fetch = require('node-fetch');

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console()
    ],
    format: winston.format.combine(
        winston.format.colorize(),
        winston.format.json()
    )
});

if (config.MONGO_CONNECTION_URL !== undefined) {
    mongoose.connect(config.MONGO_CONNECTION_URL, { useNewUrlParser: true });

    const app = express();

    middlewares(app);

    app.use('/', routes);
    fetch('https://my-json-server.typicode.com/giuliana-bezerra/demo/comments').then(console.log);

    const startServer = (port = 7755) => {
        const server = app.listen(port, function () {
            raven.config(config.LOG_SENTRY_DSN).install();

            logger.info(`server.settingsservice.initilization.running.${server.address().port}`);
        });
    };

    module.exports = startServer;
} else {
    logger.error(`server.settingsservice.initilization.database.notFound`);
    process.exit(0);
}

The problem is that I use a corporate proxy, and so fetch is waiting indefinitely.

How do I set up, preferably globally, my proxy to be used in the external Apis calls within the nodejs? I’ve done a lot of research, but the solutions offered are proxy configuration for the Node service itself, not for calls to Apis by the service.

1 answer

1


You can use the module axios to perform the request in conjunction with the module https-proxy-agent to define the proxy. To use anywhere in the application, create a module within your application. In my example I will call requisitar:

const HttpsProxyAgent = require('https-proxy-agent');

const requisitar = async (url, options = {}) => {
  const httpsAgent = process.env.PROXY_HOST ? new HttpsProxyAgent(`http://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`) : null;
  const { data } = await axios.request({ url, httpsAgent, ...options });

  return data;
};

module.exports = requisitar;

This way you can add the information from proxy environment variables and will use in calls as follows:

const requisitar = require('./requisitar');

// ...

requisitar('https://my-json-server.typicode.com/giuliana-bezerra/demo/comments').then(console.log);
  • Very good! Works for a call within my service. But what about the library calls I use on my service? (e.g. multer-Storage-cloudinary). I could not modify the libs code to use this module. There is no global way to configure this for the nodejs?

  • @Giulianabezerra worse than in this case does not work. I would look at the library documentation, but I just checked and this example you used has no mention of proxy

  • 1

    Got it, thanks for the help. I’ll mark your answer there, as it answers to the example I put in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.