在腾讯位置服务开放平台完成注册后:
在ssh终端执行以下命令
#debian系
sudo apt update
sudo apt install nodejs
sudo apt install npm
#centos
sudo yum install epel-release
sudo yum install nodejs
在服务器中,安装必要的依赖库:
npm install express
npm install axios
接下来,新建一个 app.js
文件,输入以下代码:
# app.js
const express = require("express");
const axios = require("axios");
const app = express();
// API密钥
const API_KEY = "此处替换为刚申请的密钥";
app.get("/", (req, res) => {
const clientIp = req.headers["x-forwarded-for"];
const ip = clientIp.split(",")[0].trim();
const requestedIp = req.query.ip || ip;
const url = `https://apis.map.qq.com/ws/location/v1/ip?ip=${requestedIp}&key=${API_KEY}`;
axios
.get(url)
.then((response) => {
res.json(response.data);
})
.catch((error) => {
res
.status(500)
.json({ error: "An error occurred while fetching the data" });
});
});
//监听端口
const port = 3002;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
启动服务:
node app.js
启动后,控制台会显示:
Server running on port 3002
访问 <服务器 IP>:3002
,确保服务正常运行。如果启动失败,检查 app.js
文件和密钥配置。
配置进程守护
安装pm2
npm install pm2@latest -g
通过pm2启动文件
为了确保服务在服务器重启后自动运行,可以使用 PM2 进行进程管理:
pm2 start app.js --name ip-location-service
为了通过域名访问服务,可以配置反向代理:
example.com
)。http://127.0.0.1:3002
(3002 是应用监听的端口)。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。