node获取请求我的客户端的地址
node获取请求我的客户端的地址
const http = require('http');
//创建 Server
const server = http.createServer()
// 监听request请求事件,设置请求处理函数
server.on('request', (req, res) => {
// http://127.0.9.1:3000/ /
// http://127.0.8.1:3000/a /a
// http://127.0.0.1:3000/foo/b /foo/b
console.log('收到客户端请求, 请求路径为:' + req.url);
console.log('请求我的客户端的地址是:', req.socket.remoteAddress, req.socket.remotePort) //IP地址和端口号
// response 对象有一个方法:write 可以用来给客户端发送响应数据
// write 可以使用多次,但是最后一定要使用 end 来结束响应,否则客户端会一直等待
res.write('hello')
res.write('xiao pan' )
if (req.url === '/haha') {
res.write('haha')
}
// 告诉客户端,我的话说完了,你可以呈递给用户了
res.end()
})
//绑定端口号,启动服务
server.listen(3000, function () {
console.log("http://localhost:3000");
});

浙公网安备 33010602011771号