从外部网站获取node js参数

问题描述 投票:0回答:2

我尝试创建一个nodejs服务器,它将返回ip地址值的响应

app.get('/UserIP', function(req, res) {
    console.log(req.connection.remoteAddress);
  res.send(JSON.stringify({'ip':req.connection.remoteAddress}));
});

后来我创建了一个客户端来获取这个ip地址

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 $(document).ready(function () {

    $.getJSON("http://localhost:7979/userip", function (data) {
                $('p').html('IP Address is: ' + res.ip);
    });
});
</script>
</head>
<body>
<p></p>
</body>
</html>

我无法将该 IP 获取到我的客户网站。有一些网站(例如 jsonip.com)正在使用我的代码。 请帮助我理解我哪里做错了。

javascript node.js express
2个回答
0
投票
  • 如果您的应用程序中有
    app.set('case sensitive routing', true);
    , 访问“/userip”而不是“/UserIP”将不起作用。您有
    app.get('/UserIP'
    $.getJSON("http://localhost:7979/userip"
  • 在你的 jQuery 代码中,你正在访问一个“res”对象
    + res.ip)
    ,甚至 尽管您返回的是“data
    function (data)
    对象。

0
投票

我无法获取 json 的原因是由于许可。要解决此问题,我们需要在 apt.get 中编写此代码

res.setHeader("Access-Control-Allow-Origin", "*");

没有其他解决方案帮助我。无论如何,感谢您尝试帮助我。

© www.soinside.com 2019 - 2024. All rights reserved.