// 导入所需包和模块 const fetch = require('node-fetch'); const express = require('express'); const cors = require('cors'); require('dotenv').config(); // 导入 dotenv 并加载 .env 文件 const app = express(); app.use(cors({ origin: ['https://cansin.top', 'https://blog.cansin.top', 'https://gavin-chen.top', 'https://*.gavin-chen.top'] // 指定允许跨域访问的域名 })); // 创建 Express 应用程序 app.use(express.json()); // 路由和处理程序 app.get('/weather', async (req, res) => { try { const ip = req.query.ip; // 请求后面带ip的值,格式:domain/weather?ip=xxx const weatherKey = process.env.WEATHER_API_KEY; // 从环境变量中获取 API 密钥 const locationKey = process.env.LOCATION_API_KEY; // 从环境变量中获取 API 密钥 var weatherNowJson = {}; var weatherJson = {}; var locationJson = {}; const response1 = awaitfetch(`https://apis.map.qq.com/ws/location/v1/ip?ip=${ip}&key=${locationKey}`); const data1 = await response1.json(); locationJson = data1; try { var province = data1.result.ad_info.province; var city = data1.result.ad_info.city; var district = data1.result.ad_info.district; var place = district == '' ? city : district; var adm = district == '' ? province : city; const response2 = awaitfetch(`https://geoapi.qweather.com/v2/city/lookup?location=${place}&adm=${adm}&key=${weatherKey}`); const data2 = await response2.json(); try { var cityId = data2.location[0].id; const response3 = awaitfetch(`https://devapi.qweather.com/v7/weather/now?location=${cityId}&key=${weatherKey}`); const data3 = await response3.json(); const response4 = awaitfetch(`https://devapi.qweather.com/v7/weather/24h?location=${cityId}&key=${weatherKey}`); const data4 = await response4.json(); weatherNowJson = data3; weatherJson = data4; res.json({ weatherNowJson, weatherJson, locationJson }); // 将 JSON 数据返回给前端 } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error3' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error2' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error1' }); } });
// 启动服务器 const server = app.listen(process.env.PORT || 3000, () => { const port = server.address().port; console.log(`Server is running on port ${port}`); });