获取用户IP地址并写入文件 - JavaScript & Node.js
<p>您的IP地址是:</p>
<script>
// 使用JavaScript获取IP地址
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
const ipAddress = data.ip;
const p = document.createElement('ip');
p.textContent = ipAddress;
document.body.appendChild(p);
})
.catch(error => {
console.error('获取IP地址时发生错误:', error);
});
</script>
<p>由于JavaScript是在浏览器中运行的,无法直接访问本地文件系统。要将获取的IP地址写入1.txt文件,需要使用服务器端脚本语言(如PHP、Node.js等)来处理。</p>
<p>以下是使用Node.js的示例代码:</p>
<pre><code>
const https = require('https');
const fs = require('fs');
<p>https.get('https://api.ipify.org?format=json', (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
const ipAddress = JSON.parse(data).ip;
fs.writeFile('1.txt', ipAddress, (error) => {
if (error) {
console.error('写入文件时发生错误:', error);
} else {
console.log('IP地址已写入1.txt文件');
}
});
});
}).on('error', (error) => {
console.error('获取IP地址时发生错误:', error);
});
</code></pre></p>
原文地址: https://www.cveoy.top/t/topic/n9Dd 著作权归作者所有。请勿转载和采集!