christianalfoni / webpack-express-boilerplate

A boilerplate for running a Webpack workflow in Node express
MIT License
1.39k stars 291 forks source link

how do you handle action requests to an external API? #27

Open thehashrocket opened 8 years ago

thehashrocket commented 8 years ago

I really like what you've done with this. I'm still learning react (having come from a ruby/rails and angular background). I'm wondering how you handle getting requests from an external API?

I'm looking at this article here: https://medium.com/front-end-developers/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4#.wcor87ig4

And the server.jsx file is substantially different then yours. How would you handle something like that? Would it be the same way?

EDIT: The reason I'm asking is because the app we are building will be talking a lot to a main ruby/rails API and won't be handling any data locally (or very minimal). So this is something that is weighting heavily on us.

christianalfoni commented 8 years ago

You can add http-proxy for that :-) So you use express as kind of a "middleend", where you do all the development, can fake responses etc. But you can take a path and proxy that to some external API. An example here:

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();

const development = process.env.NODE_ENV.indexOf('production') === -1;
const proxyTo = function (origin) {
  return function (req, res) {
    req.url = req.originalUrl.replace('/api', '');
    return proxy.web(req, res, {
        target: 'http://' + origin
    });
  }
};

proxy.on('error', function (err, req, res) {
  res.sendStatus(500);
});

app.get('/api/vesselspositions', authenticate, development ? require('./api/getVesselsPositions.js') : proxyTo('10.0.0.2:8087'));
app.get('/api/areas', authenticate, development ? require('./api/getAreas.js') : proxyTo('10.0.0.1:8086'));