vue前端如何获取用户ip地址?

前端需要获取用户ip地址后传给后端。有没有方法不需要进行浏览器设置的


回答:

看看这篇文章能不能解决你的问题:https://www.cnblogs.com/l-coil/p/12790668.html


回答:

必须修改浏览器配置才可以, 因为浏览器禁止了JS获取本地IP
可以给一个提示让用户修改, 你的这个项目既然是内网用, 那一就是单位或公司内部项目, 使用要求里面写明就行了, 不修改配置不给用
edge://flags/
vue前端如何获取用户ip地址?
vue前端如何获取用户ip地址?

<!DOCTYPE html>

<html>

<head>

<title>get Ip and MAC!</title>

<meta http-equiv=Content-Type content="text/html; charset=gb2312">

</head>

<body>

<script>

/**

* Get the user IP throught the webkitRTCPeerConnection

* @param onNewIP {Function} listener function to expose the IP locally

* @return undefined

*/

function getUserIP (onNewIP) { // onNewIp - your listener function for new IPs

//compatibility for firefox and chrome

var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

var pc = new myPeerConnection({

iceServers: []

}),

noop = function () { },

localIPs = {},

ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,

key;

function iterateIP (ip) {

if (!localIPs[ip]) onNewIP(ip);

localIPs[ip] = true;

}

//create a bogus data channel

pc.createDataChannel("");

// create offer and set local description

pc.createOffer().then(function (sdp) {

sdp.sdp.split('\n').forEach(function (line) {

if (line.indexOf('candidate') < 0) return;

line.match(ipRegex).forEach(iterateIP);

});

pc.setLocalDescription(sdp, noop, noop);

}).catch(function (reason) {

// An error occurred, so handle the failure to connect

});

//listen for candidate events

pc.onicecandidate = function (ice) {

if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;

ice.candidate.candidate.match(ipRegex).forEach(iterateIP);

};

}

// Usage

getUserIP(function (ip) {

alert("Got IP! :" + ip);

});

</script>

</body>

</html>

vue前端如何获取用户ip地址?

<template>

<div></div>

</template>

<script>

export default {

async mounted () {

const getIpAddress = () => {

return new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.ipify.org?format=json');

xhr.responseType = 'json';

xhr.onload = function () {

if (this.status >= 200 && this.status < 300) {

const ip = this.response.ip;

resolve(ip);

} else {

reject({

status: this.status,

statusText: this.statusText

});

}

};

xhr.onerror = function () {

reject({

status: this.status,

statusText: this.statusText

});

};

xhr.send();

});

};

let ret = await getIpAddress()

console.log(ret);

}

}

</script>


回答:

前端不行,需要通过调用服务端接口才能获取。或者一些第三方的API

以上是 vue前端如何获取用户ip地址? 的全部内容, 来源链接: utcz.com/p/934079.html

回到顶部