3

I use this react boilerplate. It's running on express web server.

I can get client IP address in JavaScript file that process in server

But I wonder how can I pass that value to React Frontend script?

Please shed me some light.

UPDATE Now, i can use it by using javascript template engine and replace IP before rendering. Here is the code

  app.get('*', (req, res) => {
    const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
      if (err) {
        res.sendStatus(404);
      } else {
        const compileStr = Mustache.render(file.toString(), { userIpAddress: ip });
        res.send(compileStr);
      }
    });
  });

However, in production, it's using sendFile() and i cannot get fs module on production :-(

const addProdMiddlewares = (app, options) => {
  const publicPath = options.publicPath || '/';
  const outputPath = options.outputPath || path.resolve(process.cwd(), 'build');

  // compression middleware compresses your server responses which makes them
  // smaller (applies also to assets). You can read more about that technique
  // and other good practices on official Express.js docs http://mxs.is/googmy
  app.use(compression());
  app.use(publicPath, express.static(outputPath));

  app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html')));
};
chaintng
  • 1,325
  • 3
  • 14
  • 26
  • you must be making server call to fetch the data, so you can return the ip from server, alternatively you can write cutsom api call which only returns client IP .. check this http://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript-only – abhirathore2006 Jul 29 '16 at 10:59

0 Answers0