【问题标题】:Need to acces Client IP not the server IP for a weather API需要访问客户端 IP 而不是天气 API 的服务器 IP
【发布时间】:2017-03-01 13:15:13
【问题描述】:

我想使用带有 express 的 node.js 创建一个服务器端应用程序。目前,我能够获取包含位置和温度的 json 文档,但是在我使用 pykite 使其在线后,应用程序只会将服务器位置提供给正在访问它的人。以下是当前形式的代码:

var express = require('express');
var app = express();
var request = require('request');



    app.get('/api/weather/current_temperature', function (req, res) {
        request('http://api.wunderground.com/api/ebb3e0cf5059cce8/conditions/q/autoip.json', function(error, response, body){
            if (!error && response.statusCode==200){
              res.setHeader('Content-Type', 'aplication/json');    
              var result = JSON.parse(body);
              res.json({ "location": result.current_observation.observation_location.city,"temperature": result.current_observation.temp_c });
            }else{
                console.log(error, response.statusCode, body);
            }
            res.end("")
        });
    });

    var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
        console.log('The app is up.');
    });

我承认我对此很陌生,但我想学习。如果可能的话,我希望在此代码中实现它的一些帮助,一种访问用户位置并确定他/她位置的天气的方法。 提前谢谢你。

P.S.:我还想要一些文档的链接,不想跳过任何内容。

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

您链接到 http://api.wunderground.com/api/YOUR_KEY/conditions/q/autoip.json 的 URL(由于您没有提供密钥而无法使用)的名称中有 autoip

这意味着它将从请求来自的任何 IP 地址返回结果。

所以你有两个选择:

  • 不要从 NodeJS 发出请求。从浏览器发出请求。 (考虑到 API 密钥的使用,这可能是不可取的,并且可能会遇到同源策略问题)。
  • 找到一个不同的 API(可能来自同一个站点),让您指定要使用的 IP 地址或位置。

【讨论】:

  • 我没有在示例代码中提供密钥,在我的代码中我有。
  • @MercuriusAltar — 这让我们很难测试代码。
猜你喜欢
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多