如何在运行于Ubuntu的VueJS 2应用中获取服务器IP地址?
获取Vue应用所在服务器IP的可行方案
因为Vue是客户端渲染框架,前端代码运行在用户浏览器中,直接调用第三方IP接口(比如你用的ipinfo.io)只能拿到发起请求的客户端IP,要获取服务器IP必须从服务端层面传递信息,以下是几种适配Ubuntu部署场景的方案:
1. 通过自有后端接口传递
如果你的Vue应用搭配了后端服务(如Node.js/Express、Python Flask等),可以在后端新增一个接口来返回服务器IP:
- 后端示例(Node.js):
const express = require('express'); const os = require('os'); const app = express(); app.get('/api/server-ip', (req, res) => { // 获取服务器内网IP(可根据需求替换为公网IP逻辑) const interfaces = os.networkInterfaces(); let serverIp = ''; for (const name of Object.keys(interfaces)) { for (const iface of interfaces[name]) { if (iface.family === 'IPv4' && !iface.internal) { serverIp = iface.address; break; } } if (serverIp) break; } // 若需要公网IP,可在后端调用第三方接口(如curl ifconfig.me)后返回 res.json({ serverIp }); }); app.listen(3000);
- 前端调用:
fetch('/api/server-ip') .then(response => response.json()) .then(data => console.log('服务器IP:', data.serverIp)) .catch(error => console.log('请求错误:', error));
2. Nginx反向代理添加响应头
如果用Nginx托管Vue应用,可在Nginx配置中添加自定义响应头传递服务器IP:
- 修改Nginx配置文件(通常在
/etc/nginx/sites-available/下):
server { listen 80; server_name your-domain.com; location / { root /path/to/your/vue/dist; try_files $uri $uri/ /index.html; # 添加服务器IP响应头 add_header X-Server-IP $server_addr; # 若前端存在跨域,需配置允许自定义头 add_header Access-Control-Expose-Headers X-Server-IP; } }
- 前端获取:
fetch('/') .then(response => { const serverIp = response.headers.get('X-Server-IP'); console.log('服务器IP:', serverIp); }) .catch(error => console.log('请求错误:', error));
修改配置后重启Nginx:sudo systemctl restart nginx
3. 静态部署时注入服务器IP
如果是纯静态部署(无后端),可以在部署阶段将服务器IP注入到Vue的静态文件中:
- 在
public/index.html中添加一个全局变量占位:
<script> window.SERVER_IP = '__SERVER_IP__'; </script>
- 部署时用脚本替换占位符(Ubuntu下可使用sed命令):
# 替换为服务器内网IP sed -i "s/__SERVER_IP__/$(hostname -I | awk '{print $1}')/" /path/to/your/vue/public/index.html # 或替换为服务器公网IP sed -i "s/__SERVER_IP__/$(curl -s ifconfig.me)/" /path/to/your/vue/public/index.html
- 前端直接读取:
console.log('服务器IP:', window.SERVER_IP);
内容的提问来源于stack exchange,提问作者D Mawer
相关产品推荐
相关产品推荐

