通过Heroku获取客户IP地址

时间:2019-12-20 15:34:14

标签: javascript node.js express heroku

我有一个带有Cloudflare的Heroku应用,我尝试根据客户端的本地化显示不同的版本。 它在开发中效果很好,但在生产中却不是(总是显示/en,而不是/fr)。 我使用express-ip npm软件包。

代码:

const express = require('express');
const router = express.Router();

const expressip = require("express-ip");

router.use(expressip().getIpInfoMiddleware);

router.get("/", function ipFrance(req, res) {
  const ipInfo = req.ipInfo;
  const ipInfoRegion = req.ipInfo.region;
  const ipInfoCountry = req.ipInfo.country;

  //var message = `Hey, you are browsing from ${ipInfoRegion}, ${ipInfoCountry}`;
  if(ipInfoCountry == "FR" || ipInfoRegion == "Wallonia") {
      res.redirect("/fr");
  } else {
      res.redirect("/en");
  }
});

module.exports = router; 

1 个答案:

答案 0 :(得分:2)

不提供基于IP地址的翻译。 There's an HTTP header for that,以及使用该标头的快速API方法req.acceptsLanguages()

router.get("/", function (req, res) {
  if (req.acceptsLanguages("fr")) {
    res.redirect("/fr");
  } else {
    res.redirect("/en");
  }
});

一些法国本地人可能喜欢用英语浏览,而世界其他地方可能更喜欢用法语浏览。让他们做出决定,不要为他们做出决定。