一、前言
在前端開發中,有時候需要獲取用戶的IP地址,以便做一些後續的處理。本文將從多個方面對Vue獲取IP地址做詳細闡述。
二、前端Vue獲取IP地址
Vue作為一種流行的前端框架,如何獲取IP地址呢?可以使用瀏覽器端Javascript來實現。具體代碼如下:
async function fetchIP() { const res = await fetch('https://api.ipify.org?format=json') const json = await res.json() return json.ip } const ip = await fetchIP() console.log(ip)
上述代碼可以通過調用ipify.org提供的API獲取本機IP地址。通過await
可以等待異步請求的結果並返回IP地址。
三、Vue獲取內網IP地址
如果需要獲取內網IP地址,只能通過客戶端進行獲取。可以使用WebRTC API來實現,代碼如下:
function getInternalIPAddress() { return new Promise(function (resolve, reject) { window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection; if (window.RTCPeerConnection) { var rtc = new RTCPeerConnection({ iceServers: [] }); if (1 || window.mozRTCPeerConnection) { rtc.createDataChannel('', { reliable: false }); }; rtc.onicecandidate = function (evt) { if (evt.candidate) grepSDP("a=" + evt.candidate.candidate); }; rtc.createOffer(function (offerDesc) { grepSDP(offerDesc.sdp); rtc.setLocalDescription(offerDesc); }, function (e) { console.warn("offer failed", e); }); var addrs = Object.create(null); addrs["0.0.0.0"] = false; var rSplit = /(^\d+|\.[^.]+)/g; function grepSDP(sdp) { var hosts = []; sdp.split('\r\n').forEach(function (line, index, arr) { if (~line.indexOf("a=candidate")) { var parts = line.split(' '), addr = parts[4], type = parts[7]; if (type === 'host') { var s = addr.split(rSplit); s.pop(); hosts.push(s.join('')); } } else if (~line.indexOf("c=")) { var parts = line.split(' '), addr = parts[2]; var s = addr.split(rSplit); s.pop(); hosts.push(s.join('')); } }); hosts.forEach(function (host) { addrs[host] = true; }); } setTimeout(function () { Object.keys(addrs).some(function (k) { if (addrs[k]) resolve(k); }); }, 1500); } else { reject("WebRTC not supported"); } }); } getInternalIPAddress().then(function (ip) { console.log(ip); }).catch(function (e) { console.error(e); });
上述代碼使用WebRTC API來獲取內網IP地址。通過調用getInternalIPAddress()
方法並使用.then()
返回結果。
四、Vue獲取服務器IP地址
如果需要獲取服務器端的IP地址,可以通過後端提供的API來獲取。以Node.js為例,可以使用以下代碼實現:
const os = require('os'); function getServerIP() { const ifaces = os.networkInterfaces(); let ip = ''; Object.keys(ifaces).forEach((ifname) => { ifaces[ifname].forEach((iface) => { if (iface.family !== 'IPv4' || iface.internal !== false) { return; } ip = iface.address; }); }); return ip; } const ip = getServerIP(); console.log(ip);
上述代碼可以通過Node.js內置的os
模塊獲取服務器端的IP地址。通過調用getServerIP()
方法即可獲取。
五、Vue獲取客戶端IP地址
如果需要獲取客戶端IP地址,可以通過後端提供的API來獲取。以Node.js為例,可以使用以下代碼實現:
const requestIp = require('request-ip'); function getClientIP(req) { const clientIp = requestIp.getClientIp(req); return clientIp; } const clientIp = getClientIP(req); console.log(clientIp);
上述代碼可以通過使用request-ip
模塊獲取客戶端IP地址。通過調用getClientIP(req)
方法傳入請求參數即可獲取。
六、Vue獲取本地IP地址
獲取本地IP地址可以通過使用Java Applet來實現。代碼如下:
var attributes = { id: 'getLocalIPAddress', code: 'GetLocalIPAddress.class', archive: 'GetLocalIPAddress.jar', width: 0, height: 0 }; var parameters = { codebase_lookup: false }; deployJava.runApplet(attributes, parameters, '1.6');
上述代碼雖然可以獲取本地IP地址,但需要先安裝Java Applet並在前端使用<applet>
標籤來調用。因此不建議使用。
七、Vue獲取本地IP地址
如果需要獲取用戶的IP地址,可以通過後端提供的API來獲取。以Node.js為例,可以使用以下代碼實現:
const requestIp = require('request-ip'); function getUserIP(req) { const userIp = requestIp.getClientIp(req); return userIp; } const userIp = getUserIP(req); console.log(userIp);
上述代碼可以通過使用request-ip
模塊獲取用戶IP地址。調用getUserIP(req)
方法傳入請求參數即可獲取。
八、Vue獲取客戶端IP地址(使用window對象)
如果需要通過window對象來獲取客戶端IP地址,可以使用以下代碼實現:
function getClientIP() { let ip = '' fetch('https://api.ipify.org') .then((response) => { return response.text() }) .then((data) => { ip = data }) .catch(() => {}); return ip } const clientIp = getClientIP(); console.log(clientIp);
上述代碼可以通過調用ipify.org提供的API獲取本機IP地址,通過fetch
請求返回結果。但由於fetch是異步的,需要使用Promise
來獲取返回結果。
九、Vue自動獲取IP地址上不了網
如果自動獲取IP地址失敗無法上網,可以手動獲取本機IP地址。可以使用命令行工具(如Windows下的cmd或Linux下的Terminal)來實現,代碼如下:
ipconfig (Windows) ifconfig (Linux)
上述代碼可以手動打開命令行工具,並輸入相應指令來查看本機IP地址。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/236724.html