I am calling API. Below are 2 code snipets.
I have haproxy installed in my linux machine to ..
// Superagent approch
import superagent from 'superagent';
app.get('/api/getProducts', (req, res) => {
const endPoint = '127.0.0.1:8500/getProducts';
superagent.get(endPoint)
.timeout(1000)
.end((error, response) => {
const { body, text } = response || {};
if (response) {
ret = text || body;
} else if (error) {
ret = error;
}
return res.send(ret);
});
});
// http proxy approch
import { createProxyServer } from 'http-proxy';
const proxy = createProxyServer({
target: '127.0.0.1',
proxyTimeout: 1000,
});
app.get('/api/getProducts', (req, res) => {
proxy.web(req, res);
});
proxy.on('error', (err, req, res) => {
const json = { error: 'proxy_error', message: err.message };
res.end(JSON.stringify(json));
});
I would use neither of these two solutions.
I would refactor using node-fetch.
Why?
Because node-fetch has the same API as fetch in the browsers, which is sleek and promise based.
If you want to use web-sockets then go with http-proxy it has good support for web-sockets. Or otherwise if normal http calls are required any library will work, select library you are more comfortable with.
As Eric mentioned, node-fetch is prominent for this.
I don't think using HAProxy for calling 3rd party APIs is normal. I don't think there is any issue with either of your current tools, but I would use axios because you can create specialized sub-instances (perfect for APIs!).
const instance = axios.create({ baseURL: 'some-api-domain.com/api', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); // every HTTP request made using the instance object // will include the specified defaults export default instance// other file import someApi from './some-api' export async function getContacts() { const response = await someApi.get("contacts") return response.data } export async function addContact(data) { const response = await someApi.post("contacts", data) return response.data } export async function getContact(id) { const response = await someApi.get(`contacts/${id}`) return response.data }Axios is isomorphic (works in browser and in serverside), also checkout the middlewares (called interceptors).
I recommend not using fetch because fetch is very low-level and does almost nothing right by default for typical 3rd party JSON APIs. medium.com/@shahata/why-i-wont-be-using-fetch-api…