Use proxy in nodejs to access external apis
I have a service in 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 coorporate proxy, and so the fetch is waiting indefinitely.
How do I configure, preferably globally, my proxy to be used for external API calls within nodejs? I've done a lot of research, but the solutions offered are proxy configuration for the node service itself, and not for calls to apis by service.
0
Author: Giuliana Bezerra, 2019-05-07
1 answers
You can use the module axios
to perform the request together with the module https-proxy-agent
to set 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 of proxy
in the environment variables and will use in the calls as follows:
const requisitar = require('./requisitar');
// ...
requisitar('https://my-json-server.typicode.com/giuliana-bezerra/demo/comments').then(console.log);
1
Author: Sorack, 2019-05-07 13:54:26