js根据当前请求获取ip地址

function getIP() {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();
		xhr.open('GET', 'https://api.ipify.org?format=json');
		xhr.onload = () => {
			if (xhr.status === 200) {
				const response = JSON.parse(xhr.responseText);
				resolve(response.ip);
			} else {
				reject('Failed to get IP address');
			}
		};
	xhr.send();
	});
}


getIP().then(ip => console.log(ip)).catch(error => console.error(error));

你可能感兴趣的:(JavaScript,javascript)