简单的IP查询页面制作(二)
hhs
撰写于 2024年 06月 04 日

接上一个文章

https://xwean.com/1959.html

做个代码备份

2024-06-04T04:05:47.png

NGINX 新增代理→nginx.conf


        # 新增Node.js应用的反向代理配置
        location /get-ip-info {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location /get-weather {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }


前端→index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>看看天气咋样</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            flex-direction: column;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
            margin-bottom: 20px; /* 与底部文字保持距离 */
        }

        .info-box {
            background-color: #E9ECEF;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .footer {
            color: black; /* 设置底部文字颜色 */
            font-size: 12px; /* 设置底部文字大小 */
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>我的天气!</h1>
        <div id="ip" class="info-box">IP地址:加载中...</div>
        <div id="location" class="info-box">位置:加载中...</div>
        <div id="weather" class="info-box">天气:加载中...</div>
        <div id="time" class="info-box">当前时间:加载中...</div>
    </div>
    <div class="footer">
        私人网盘正在开发中....
        ozxuu@outlook.com
    </div>
    <script>
        // 获取IP和位置信息
        fetch('/get-ip-info')
            .then(response => response.json())
            .then(data => {
                document.getElementById('ip').textContent = `IP地址:${data.ip}`;
                document.getElementById('location').textContent = `位置:${data.country} - ${data.city} - ${data.region}`;
                
                // 使用获取到的位置信息请求天气数据
                return fetch(`/get-weather?city=${data.city}`);
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('weather').textContent = `天气:${data.weather[0].main}, 温度:${data.main.temp}°C`;
            })
            .catch(error => console.error('获取信息失败', error));

        // 显示当前时间
        document.getElementById('time').textContent = `当前时间:${new Date().toLocaleTimeString()}`;
    </script>
</body>
</html>

后端→index.js


require('dotenv').config(); // 加载环境变量

const express = require('express');
const fetch = require('node-fetch');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 创建一个写入流,并将日志写入到指定文件中
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

// 设置morgan日志记录中间件,将日志输出到文件中
app.use(morgan('combined', { stream: accessLogStream }));

// 获取IP地址信息的路由
app.get('/get-ip-info', async (req, res) => {
    const ipinfoToken = process.env.IPINFO_TOKEN;
    // 获取请求者的IP地址
    const visitorIp = req.headers['x-forwarded-for']?.split(',').shift() || req.connection.remoteAddress;

    if (!visitorIp) {
        res.status(500).json({ error: '无法获取位置IP' });
        return;
    }

    try {
        // 调用IPinfo API获取访问者的IP地址信息
        const ipinfoResponse = await fetch(`https://ipinfo.io/${visitorIp}?token=${ipinfoToken}`);
        const ipinfoData = await ipinfoResponse.json();

        // 如果返回的数据不包含IP信息,则停止并返回错误
        if (!ipinfoData || !ipinfoData.ip) {
            res.status(500).json({ error: '无法获取位置IP' });
            return;
        }

        res.json(ipinfoData); // 将访问者的IP地址信息发送给前端
    } catch (error) {
        console.error('Error fetching IP info:', error);
        res.status(500).json({ error: 'Server Error' });
    }
});

// 获取天气信息的路由
app.get('/get-weather', async (req, res) => {
    const openWeatherMapApiKey = process.env.OPENWEATHERMAP_API_KEY;
    const city = req.query.city; // 从查询参数中获取城市名称

    if (!city) {
        res.status(400).json({ error: '城市名称是必需的' });
        return;
    }

    try {
        // 根据城市名称获取天气信息
        const weatherResponse = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${openWeatherMapApiKey}&units=metric`);
        const weatherData = await weatherResponse.json();

        // 如果API返回了错误
        if (weatherData.cod != 200) {
            res.status(weatherData.cod).json({ error: weatherData.message });
            return;
        }

        res.json(weatherData); // 将天气信息发送给前端
    } catch (error) {
        console.error('Error fetching weather data:', error);
        res.status(500).json({ error: 'Server Error' });
    }
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

其他→package.json


{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.5",
    "express": "^4.18.3",
    "morgan": "^1.10.0",
    "node-fetch": "^2.6.1"
  }
}

全部地址---百度网盘---我的资源---简单IP地址看天气---压缩包

简单的IP查询页面制作(二)

接上一个文章

https://xwean.com/1959.html

做个代码备份

2024-06-04T04:05:47.png

NGINX 新增代理→nginx.conf


        # 新增Node.js应用的反向代理配置
        location /get-ip-info {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location /get-weather {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }


前端→index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>看看天气咋样</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            flex-direction: column;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
            margin-bottom: 20px; /* 与底部文字保持距离 */
        }

        .info-box {
            background-color: #E9ECEF;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .footer {
            color: black; /* 设置底部文字颜色 */
            font-size: 12px; /* 设置底部文字大小 */
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>我的天气!</h1>
        <div id="ip" class="info-box">IP地址:加载中...</div>
        <div id="location" class="info-box">位置:加载中...</div>
        <div id="weather" class="info-box">天气:加载中...</div>
        <div id="time" class="info-box">当前时间:加载中...</div>
    </div>
    <div class="footer">
        私人网盘正在开发中....
        ozxuu@outlook.com
    </div>
    <script>
        // 获取IP和位置信息
        fetch('/get-ip-info')
            .then(response => response.json())
            .then(data => {
                document.getElementById('ip').textContent = `IP地址:${data.ip}`;
                document.getElementById('location').textContent = `位置:${data.country} - ${data.city} - ${data.region}`;
                
                // 使用获取到的位置信息请求天气数据
                return fetch(`/get-weather?city=${data.city}`);
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('weather').textContent = `天气:${data.weather[0].main}, 温度:${data.main.temp}°C`;
            })
            .catch(error => console.error('获取信息失败', error));

        // 显示当前时间
        document.getElementById('time').textContent = `当前时间:${new Date().toLocaleTimeString()}`;
    </script>
</body>
</html>

后端→index.js


require('dotenv').config(); // 加载环境变量

const express = require('express');
const fetch = require('node-fetch');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 创建一个写入流,并将日志写入到指定文件中
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

// 设置morgan日志记录中间件,将日志输出到文件中
app.use(morgan('combined', { stream: accessLogStream }));

// 获取IP地址信息的路由
app.get('/get-ip-info', async (req, res) => {
    const ipinfoToken = process.env.IPINFO_TOKEN;
    // 获取请求者的IP地址
    const visitorIp = req.headers['x-forwarded-for']?.split(',').shift() || req.connection.remoteAddress;

    if (!visitorIp) {
        res.status(500).json({ error: '无法获取位置IP' });
        return;
    }

    try {
        // 调用IPinfo API获取访问者的IP地址信息
        const ipinfoResponse = await fetch(`https://ipinfo.io/${visitorIp}?token=${ipinfoToken}`);
        const ipinfoData = await ipinfoResponse.json();

        // 如果返回的数据不包含IP信息,则停止并返回错误
        if (!ipinfoData || !ipinfoData.ip) {
            res.status(500).json({ error: '无法获取位置IP' });
            return;
        }

        res.json(ipinfoData); // 将访问者的IP地址信息发送给前端
    } catch (error) {
        console.error('Error fetching IP info:', error);
        res.status(500).json({ error: 'Server Error' });
    }
});

// 获取天气信息的路由
app.get('/get-weather', async (req, res) => {
    const openWeatherMapApiKey = process.env.OPENWEATHERMAP_API_KEY;
    const city = req.query.city; // 从查询参数中获取城市名称

    if (!city) {
        res.status(400).json({ error: '城市名称是必需的' });
        return;
    }

    try {
        // 根据城市名称获取天气信息
        const weatherResponse = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${openWeatherMapApiKey}&units=metric`);
        const weatherData = await weatherResponse.json();

        // 如果API返回了错误
        if (weatherData.cod != 200) {
            res.status(weatherData.cod).json({ error: weatherData.message });
            return;
        }

        res.json(weatherData); // 将天气信息发送给前端
    } catch (error) {
        console.error('Error fetching weather data:', error);
        res.status(500).json({ error: 'Server Error' });
    }
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

其他→package.json


{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.5",
    "express": "^4.18.3",
    "morgan": "^1.10.0",
    "node-fetch": "^2.6.1"
  }
}

全部地址---百度网盘---我的资源---简单IP地址看天气---压缩包


下一篇
没有了
赞 (1)

猜您想看

评论区(暂无评论)

这里空空如也,快来评论吧~

我要评论